iOS copy, mutableCopy, strong
copy & mutableCopy
1、 非容器对象
- 对不可变对象复制,copy是指针复制(浅拷贝)和mutableCopy就是对象复制(深拷贝)。
- 对可变对象复制,copy和mutableCopy都是深拷贝,但是copy返回的对象是不可变的。
NSMutableString *str = [NSMutableString stringWithFormat:@"abc"];
NSString *copyStr = [str copy];
NSMutableString *mutableCopyStr = [str mutableCopy];
[str appendString:@"def"];
NSLog(@"%p %p %p", str, copyStr, mutableCopyStr);
NSLog(@"%@ %@ %@", str, copyStr, mutableCopyStr);
结果:
对于可变对象NSMutableString *str,copy 和mutableCopy均为深拷贝。
NSString *str = [NSString stringWithFormat:@"abc"];
NSString *copyStr = [str copy];
NSString *mutableCopyStr = [str mutableCopy];
NSLog(@"%p %p %p", str, copyStr, mutableCopyStr);
结果:
对于不可变对象copyStr和str指向相同地址,为浅拷贝;mutableCopy为深拷贝。
2、 容器对象
对于容器本身,同非容器对象。
但是,对于容器内的对象,则都是指针复制。真正的深拷贝(即容器本身、容器内的对象均为深拷贝),实现方式如下:
NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originArray]];
originArray-待拷贝数组
copy & strong
在Objective-C的ARC模式中,Objective-C默认声明的一个对象就为__strong,即:
id obj1 = [[NSObject alloc] init];
和
id __strong obj1 = [[NSObject alloc] init];
是等价的。
NSMutableString *str = [NSMutableString stringWithFormat:@"abc"];
NSString *copyStr = [str copy];
NSString *str2 = str;
[str appendString:@"def"];
NSLog(@"%p %p %p", str, copyStr, str2);
NSLog(@"%@ %@ %@", str, copyStr, str2);
结果:
str2实际是属于强引用, 与str指向相同地址。
iOS setter管理
- (NSString *)string {
return _string;
}
In the ‘set’ method or setter, the value we assign could be disposed of at any time, so we have to take ownership of the object to make sure this won’t happen.
- (void)setString:(NSString *)newString
{
[newString retain];
[_string release];
// Make the new assignment.
_string = newString;
}
参考:
[1] OS学习—强引用(__strong)和 弱引用(__weak)
http://my.oschina.net/are1ofblog/blog/394342?fromerr=ua7RsURQ
[2] 浅拷贝、深拷贝(Copy、MutableCopy)
http://www.cocoachina.com/bbs/read.php?tid-135884.html
[3] NSString属性什么时候用copy,什么时候用strong?
http://www.cocoachina.com/ios/20150512/11805.html
[4] iOS Memory Management: The Manual-Retain-Release Model
http://blog.teamtreehouse.com/ios-memory-management-part-1