Objective-C 学习笔记7 复制 NSCopying 协议

Objective-C 复制 NSCopying 协议

头文件

//
//  samplecopy.h
//  sample004
//
//  Created by echoliu on 13-1-25.
//  Copyright (c) 2013年 echoliu. All rights reserved.
//

#import <Foundation/Foundation.h>
//NSCopying 协议
@interface samplecopy : NSObject<NSCopying>
{
    int width;
    int height;
}
-(void)print;
-(void)setWidth:(int) a andHeight:(int)b;
@end

实现文件

//
//  samplecopy.m
//  sample004
//
//  Created by echoliu on 13-1-25.
//  Copyright (c) 2013年 echoliu. All rights reserved.
//

#import "samplecopy.h"

@implementation samplecopy
-(id)copyWithZone:(NSZone *)zone{
    id  ss=[[samplecopy allocWithZone:zone] init];
    [ss setWidth:width andHeight:height];
    return  ss;
}
-(void)setWidth:(int)a andHeight:(int)b{
    width=a;
    height=b;
}
-(void)print{
    NSLog(@"this is copy class %d %d",width,height);
}
@end

main测试

//
//  main.m
//  sample004
//
//  Created by echoliu on 13-1-24.
//  Copyright (c) 2013年 echoliu. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "samplecopy.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...

        samplecopy * samp1=[[samplecopy alloc] init];
        [samp1 setWidth:100 andHeight:200];
        samplecopy * samp2;
        samp2=[samp1 copy];
        //samp2=samp1;
        [samp1 print];
        [samp2 print];
        [samp1 setWidth:300 andHeight:500];
        [samp1 print];
        [samp2 print];
        [samp2 setWidth:90 andHeight:80];
        
        [samp1 print];
        [samp2 print];



        
    }
    return 0;
}

观察不同的输出

2013-01-25 16:28:08.553 sample004[7480:303] this is copy class 100 200
2013-01-25 16:28:08.554 sample004[7480:303] this is copy class 100 200
2013-01-25 16:28:08.554 sample004[7480:303] this is copy class 300 500
2013-01-25 16:28:08.555 sample004[7480:303] this is copy class 100 200
2013-01-25 16:28:08.556 sample004[7480:303] this is copy class 300 500
2013-01-25 16:28:08.556 sample004[7480:303] this is copy class 90 80

 

posted on 2013-01-25 16:31  ios开发达人  阅读(1447)  评论(0)    收藏  举报