深拷贝浅拷贝

所谓的深拷贝和浅拷贝只有指针才存在这样的概念。

.h文件 Person类

#import <Foundation/Foundation.h>



@interface Person : NSObject<NSCopying>

{

    int age;

    NSString *name;

}



@property(nonatomic,assign) int age;

@property(nonatomic,retain) NSString *name;



@end

.m文件

#import "Person.h"



@implementation Person



@synthesize age;

@synthesize name;



- (id)init

{

    self = [super init];

    if (self) {

        self.age=20;

        self.name=@"xiaoming";

    }

    return self;

}



- (void)dealloc

{

    [name release];

    [super dealloc];

}



-(id)copyWithZone:(NSZone *)zone

{

    Person *p=[[Person alloc]init];

    

    p.age= self.age;

//    p.name=self.name;             //浅拷贝

 

    p.name=[self.name copy];    //深拷贝

    

    return p;

}

@end

主函数

#import <Foundation/Foundation.h>

#import "Person.h"



int main(int argc, const char * argv[])

{



    @autoreleasepool {

        Person *per=[[Person alloc]init];

        NSLog(@"%d,%@",per.age,per.name);

        

        NSMutableString *str=[NSMutableString stringWithFormat:@"xiaoming"];

        per.name=str;

        per.age=21;

        NSLog(@"%d,%@",per.age,per.name);

        

        Person *per2=[[Person alloc]init];

        per2=[per copy];

        NSLog(@"%d,%@",per2.age,per2.name);



        [str appendString:@"2"];

        NSLog(@"%d,%@",per.age,per.name);

        NSLog(@"%d,%@",per2.age,per2.name);

        

        [per release];

        [per2 release];





    }

    return 0;

}

  

你可能感兴趣的:(深拷贝)