copy and copyWithZone

定义一个Person类

#import 

@interface Person : NSObject

@property (nonatomic, strong) NSString *strongName;

@property (nonatomic, copy) NSString *coName;

@end

然后在VC中调用Person

- (void)testPerson {
    NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
    
    Person *p = [[Person alloc] init];
    p.strongName = someName;
    p.coName = someName;
    
    [someName setString:@"Debajit"];
//    The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but @"Chris" if the property is marked copy.
//    Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)
    NSLog(@"strongName: %@",p.strongName);
    NSLog(@"copyName : %@",p.coName);
}
输出:
//     strongName: Debajit
//     copyName : Chris

使用strong修饰的name字符串在赋值之后,如果字符串改变,会影响之前name的内容。
使用copy修饰的字符串在值修改之后则不会受到影响。

一个类要使用copy方法需要实现copyWithZone的协议
定义一个UserInfo类

#import 

@interface UserInfo : NSObject 

@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;

- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;

@end
#import "UserInfo.h"

@implementation UserInfo

- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
    
    if (self = [super init]) {
        self.firstName = [firstName copy];
        self.lastName = [lastName copy];
    }
    
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    
    UserInfo *info = [[[self class] allocWithZone:zone] initWithFirstName:self.firstName lastName:self.lastName];
    return info;
}


@end

实现copyWithZone的协议方法。
在vc中调用UserInfo

- (void)testUserInfo {
    
    
    UserInfo *obj1 = [[UserInfo alloc] initWithFirstName:@"zhang" lastName:@"san"];
    
    NSLog(@"obj1 address : %p  %@,%@",obj1,obj1.firstName,obj1.lastName);
    
    UserInfo *copyObj1 = [obj1 copy]; //复制一个新对象,到一个新的内存地址,并把值一并复制过去。
    
    NSLog(@"copyObj1 address : %p  %@,%@",copyObj1,copyObj1.firstName,copyObj1.lastName);
    
    copyObj1.firstName = @"li";
    copyObj1.lastName = @"si";
    NSLog(@"obj1 address : %p  %@,%@",obj1,obj1.firstName,obj1.lastName);
    NSLog(@"copyObj1 address : %p  %@,%@",copyObj1,copyObj1.firstName,copyObj1.lastName);
  
输出:
 obj1 address : 0x60400002e8c0  zhang,san
 copyObj1 address : 0x60800002fe80  zhang,san
 obj1 address : 0x60400002e8c0  zhang,san
 copyObj1 address : 0x60800002fe80  li,si
}

你可能感兴趣的:(copy and copyWithZone)