Objective C assign© & retain区别

时间:2023-03-09 04:13:39
Objective C   assign&copy & retain区别

什么是assign,copy,retain之间的区别?

  • assign: 简单赋值,不更改索引计数(Reference Counting)。
  • copy: 建立一个索引计数为1的对象,然后释放旧对象
  • retain:释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1

retain是指针拷贝,copy是内容拷贝

比如一个Car对象,地址为0×1111

Copy到另外一个NSString之后,地址为0×2222,内容相同,新的对象retain为1,旧有对象没有变化

retain到另外一个NSString之后,地址相同(建立一个指针,指针拷贝),内容当然相同,这个对象的retain值+1

- (void)setName:(NSString *)newName {
if (name != newName) {
[name release];
name = [newName retain];
// name’s retain count has been bumped up by 1
}
}

对于NSString、NSDictianary等数据型是很特殊的,见下示例

NSLog(@”COPY retain 差异测试”);

NSString * t3 = [[NSString alloc] initWithFormat:@”%@”,@”t3″];
NSLog(@”变量t3=%@ count=%d 地址=%lx “,t3,[t3 retainCount],&t3);
NSLog(@”t4 COPY t3″);
NSString * t4 = [t3 copy];
NSString * t5 = t3;
NSLog(@”变量t3=%@ count=%d 地址=%lx “,t3,[t3 retainCount],&t3);
NSLog(@”变量t4=%@ count=%d 地址=%lx “,t4,[t4 retainCount],&t4);
NSLog(@”变量t5=%@ count=%d 地址=%lx “,t5,[t5 retainCount],&t5);
NSLog(@”t3 retain”);
[t3 retain];

NSLog(@”变量t3=%@ count=%d 地址=%lx “,t3,[t3 retainCount],&t3);
NSLog(@”变量t4=%@ count=%d 地址=%lx “,t4,[t4 retainCount],&t4);
NSLog(@”变量t5=%@ count=%d 地址=%lx “,t5,[t5 retainCount],&t5);

NSLog(@”t3 release”);
[t3 release];
//[t4 release];
NSLog(@”变量t3=%@ count=%d 地址=%lx “,t3,[t3 retainCount],&t3);
NSLog(@”变量t4=%@ count=%d 地址=%lx “,t4,[t4 retainCount],&t4);
NSLog(@”变量t5=%@ count=%d 地址=%lx “,t5,[t5 retainCount],&t5);

NSLog(@”t4 release”);
[t4 release];
//[t4 release];
NSLog(@”变量t3=%@ count=%d 地址=%lx “,t3,[t3 retainCount],&t3);
NSLog(@”变量t4=%@ count=%d 地址=%lx “,t4,[t4 retainCount],&t4);
NSLog(@”变量t5=%@ count=%d 地址=%lx “,t5,[t5 retainCount],&t5);

2010-06-04 18:29:19.177 memmanage[2926:a0f] COPY retain 差异测试
2010-06-04 18:29:19.177 memmanage[2926:a0f] 变量t3=t3 count=1 地址=7fff5fbff750
2010-06-04 18:29:19.178 memmanage[2926:a0f] t4 COPY t3
2010-06-04 18:29:19.178 memmanage[2926:a0f] 变量t3=t3 count=2 地址=7fff5fbff750
2010-06-04 18:29:19.178 memmanage[2926:a0f] 变量t4=t3 count=2 地址=7fff5fbff748
2010-06-04 18:29:19.179 memmanage[2926:a0f] 变量t5=t3 count=2  地址=7fff5fbff740
2010-06-04 18:29:19.179 memmanage[2926:a0f] t3 retain
2010-06-04 18:29:19.180 memmanage[2926:a0f] 变量t3=t3 count=3 地址=7fff5fbff750
2010-06-04 18:29:19.180 memmanage[2926:a0f] 变量t4=t3 count=3 地址=7fff5fbff748
2010-06-04 18:29:19.180 memmanage[2926:a0f] 变量t5=t3 count=3 地址=7fff5fbff740
2010-06-04 18:29:19.181 memmanage[2926:a0f] t3 release
2010-06-04 18:29:19.182 memmanage[2926:a0f] 变量t3=t3 count=2 地址=7fff5fbff750
2010-06-04 18:29:19.182 memmanage[2926:a0f] 变量t4=t3 count=2 地址=7fff5fbff748
2010-06-04 18:29:19.183 memmanage[2926:a0f] 变量t5=t3 count=2 地址=7fff5fbff740
2010-06-04 18:29:19.183 memmanage[2926:a0f] t4 release
2010-06-04 18:29:19.184 memmanage[2926:a0f] 变量t3=t3 count=1 地址=7fff5fbff750
2010-06-04 18:29:19.184 memmanage[2926:a0f] 变量t4=t3 count=1 地址=7fff5fbff748
2010-06-04 18:29:19.185 memmanage[2926:a0f] 变量t5=t3 count=1 地址=7fff5fbff740