Cod*_*der 1 iphone memory-management retain ios assign
我观察到以下行为.
取了两个属性变量.
@property (nonatomic, retain) NSString *stringOne;
@property (nonatomic, assign) NSString *stringTwo;
Run Code Online (Sandbox Code Playgroud)
在.m文件中写下代码..
NSMutableString *localstring= [[NSMutableString alloc] initWithString:@"test"];
self.stringOne = localstring;
NSLog(@"localstring = %d", [string retainCount]);
NSLog(@"string one retain count = %d", [self.stringOne retainCount]);
self.stringTwo = localstring;
NSLog(@"localstring = %d", [localstring retainCount]);
NSLog(@"string two retain count = %d", [self.stringTwo retainCount]);
Run Code Online (Sandbox Code Playgroud)
由于alloc,localstring保留计数为1.现在我给了self.stringOne = localString.
由于stringOne的retain属性,localstring的保留计数将变为2.现在我给了self.stringTwo = localString.
即使在这里,localstring保留计数也会增加1.请注意,我已将assign属性赋予stringTwo.实际上,localstring或stringTwo的保留计数不应该增加1,因为它是assign属性.如果我错了,请纠正我.
谢谢Jithen
倾倒retainCount; 它没用. http://www.whentouseretaincount.com/
您混淆的根源在于不了解指针的工作原理.像这样修改你的代码:
@interface BBQ:NSObject
@property (nonatomic, retain) NSString *stringOne;
@property (nonatomic, assign) NSString *stringTwo;
@end
@implementation BBQ
- (void) burn
{
NSMutableString *localstring= [[NSMutableString alloc] initWithString:@"test"];
self.stringOne = localstring;
NSLog(@"localstring = %p", localstring);
NSLog(@"string one = %p", self.stringOne);
self.stringTwo = localstring;
NSLog(@"localstring = %p", localstring);
NSLog(@"string two = %p", self.stringTwo);
}
@end
Run Code Online (Sandbox Code Playgroud)
它会喷出这样的东西:
2013-04-11 08:48:13.770 asdffadsfasddfsa[18096:303] localstring = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] string one = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] localstring = 0x10010aaf0
2013-04-11 08:48:13.772 asdffadsfasddfsa[18096:303] string two = 0x10010aaf0
Run Code Online (Sandbox Code Playgroud)
只有一个字符串实例在播放; localstring,stringOne和stringTwo所有人都只引用了一个NSMUtableString实例.
因此,你会看到+1 RC 是一个字符串实例为alloc,一为分配到stringOne属性和没有变化stringTwo.
(RC只应该根据增量进行推理;如果保留一个对象,则需要在不再需要该对象时将其与一个版本进行平衡.该对象可能被其他东西保留是无关紧要的.)
| 归档时间: |
|
| 查看次数: |
1765 次 |
| 最近记录: |