【发布时间】:2012-05-18 11:32:25
【问题描述】:
我从苹果文档中读到的内容,retain 会增加 1,release 会减少 1。这对我来说非常清楚。
但是在复制和保留的情况下我有点困惑。
让我用我正在尝试的代码解释一下。
属性---
@property(nonatomic, retain) NSMutableString *a;
@property(nonatomic, copy) NSMutableString *b;
@synthesize a = _a ,b = _b
a=[[NSMutableString alloc]initWithString:@"Hello Ankit"];
NSLog(@"a memory location A - %p", &a );
b=[[NSMutableString alloc]initWithString:@"Hello Nigam"];
NSLog(@"a memory location B- %p", &b );
c= [[NSMutableString alloc]initWithString:@"Ankit Nigam"];
NSLog(@"a memory location C %p",&c);
NSMutableString *temp =[[NSMutableString alloc]initWithString:@"hey"];
NSLog(@"temp = %@ %p",temp,&temp);
self.b = temp;
NSLog(@"B is now %@ %p",self.b,&b);
self.a = temp;
NSLog(@"A is now %@ %p",self.a,&a);
And i get the output as -- - -
2012-05-10 03:24:34.756 retainCountTest[2655:f803] a memory location A - 0x6d314fc
2012-05-10 03:24:34.757 retainCountTest[2655:f803] a memory location B- 0x6d31500
2012-05-10 03:24:34.764 retainCountTest[2655:f803] a memory location C 0x6d31504
2012-05-10 03:24:34.764 retainCountTest[2655:f803] temp = hey 0xbfffdd04
2012-05-10 03:24:34.764 retainCountTest[2655:f803] B is now hey 0x6d31500
2012-05-10 03:24:34.765 retainCountTest[2655:f803] A is now hey 0x6d314fc
但据我从文档中了解到,保留对象必须具有相同的内存地址,而复制对象将创建一个具有不同内存位置的新对象。
当我再次将日志更改为 ---
self.b = temp;
NSLog(@"B is now %@ %p",self.b,&_b);
self.a = temp;
NSLog(@"A is now %@ %p",self.a,&_a);
It return me a complete different memory location for both the object.
2012-05-10 03:28:49.905 retainCountTest[2688:f803] a memory location A - 0x6d4a4ac
2012-05-10 03:28:49.906 retainCountTest[2688:f803] a memory location B- 0x6d4a4b0
2012-05-10 03:28:49.907 retainCountTest[2688:f803] a memory location C 0x6d4a4b4
2012-05-10 03:28:49.907 retainCountTest[2688:f803] temp = hey 0xbfffdd04
2012-05-10 03:28:49.908 retainCountTest[2688:f803] B is now hey 0x6d4a4c0
2012-05-10 03:28:49.908 retainCountTest[2688:f803] a is now hey 0x6d4a4bc
任何人都可以帮助我理解这些保留和复制的完整概念。还有为什么我会得到这些意想不到的结果。
非常感谢。
【问题讨论】:
-
注意
&_b是变量_b的地址而不是对象的地址;因此,&_b和&_a无论如何都会有所不同,并且很容易在同一方法的后续运行中可能会有所不同,具体取决于调用堆栈。 -
+1 和@ankit,这适用于您对
&的所有使用。你没有记录你认为自己是什么。 -
Objective-C 对象本质上是指向内存结构的指针。使用 NSLog 时,您可以只使用
NSLog(@"%p", object);,它将打印指针位置而不是对象的 -description 方法。 -
坦率地说,如果你现在还没有弄清楚保留/释放的东西,你应该跳过它直接去 ARC。
-
这并不难: - 保留传递给您的您希望作为全局对象拥有的对象,并在完成后释放它。 - 复制您想为自己保留的对象,并仅在您想为其保留弱引用时分配对象。 ARC 是同一个游戏——不同的名字。事实上,我认为对于桥接和弱类型等,ARC 是一个可怕的选择。首先需要改进。
标签: iphone objective-c properties retain