深拷贝与前拷贝的理解

深.浅拷贝
copy/mutableCopy NSString

NSString *string = @"汉斯哈哈哈";
// 没有产生新对象
NSString *copyString = [string copy];
// 产生新对象
NSMutableString *mutableCopyString = [string mutableCopy];

NSLog(@"string = %p copyString = %p mutableCopyString = %p", string, copyString, mutableCopyString);

string = 0x1020e42b0 
 copyStirng = 0x1020e42b0 
 mutableCopyString = 0x7fe711c23370

copy/mutableCopy NSMutableString

NSMutableString *string = [NSMutableString stringWithString:@"汉斯哈哈哈"];

// 产生新对象
NSString *copyString = [string copy];
// 产生新对象
NSMutableString *mutableCopyString = [string mutableCopy];

NSLog(@"string = %p copyString = %p mutableCopyString = %p", string, copyString, mutableCopyString);

 string = 0x7fe711d911f0 
 copyStirng = 0x1020e42b0 
 mutableCopyString = 0x7fe711d09410

注意:其他对象NSArray、NSMutableArray 、NSDictionary、NSMutableDictionary一样适用

#import @interface HSPerson : NSObject@property (nonatomic, copy) NSString *name;@end

NSMutableString *string = [NSMutableString stringWithFormat:@"汉斯哈哈哈"];
HSPerson *person = [[HSPerson alloc] init];
person.name = string;// 不能改变person.name的值,因为其内部copy新的对象
[string appendString:@" hans"]; NSLog(@"name = %@", person.name);



@property (nonatomic, strong) NSString *name;

NSMutableString *string = [NSMutableString stringWithFormat:@"汉斯哈哈哈"];
HSPerson *person = [[HSPerson alloc] init];
person.name = string;// 可以改变person.name的值,因为其内部没有生成新的对象
[string appendString:@" hans"];
NSLog(@"name = %@", person.name);



你可能感兴趣的:(深拷贝与前拷贝的理解)