我有以下示例类:
Test.h:
@interface Test : UIButton {
NSString *value;
}
- (id)initWithValue:(NSString *)newValue;
@property(copy) NSString *value;
Test.m:
@implementation Test
@synthesize value;
- (id)initWithValue:(NSString *)newValue {
[super init];
NSLog(@"before nil value has retain count of %d", [value retainCount]);
value = nil;
NSLog(@"on nil value has retain count of %d", [value retainCount]);
value = newValue;
NSLog(@"after init value has retain count of %d", [value retainCount]);
return self;
}
产生以下输出:
2008-12-31 09:31:41.755 Concentration[18604:20b] before nil value has retain count of 0
2008-12-31 09:31:41.756 Concentration[18604:20b] on nil value has retain count of 0
2008-12-31 09:31:41.757 Concentration[18604:20b] after init value has retain count of 2147483647
我这样称呼它:
Test *test = [[Test alloc] initWithValue:@"some text"];
值不应该保留计数为1吗?我想念什么?
谢谢你的帮助。
最佳答案
您已经引用了一个不可变的字符串。赋值不需要复制值(字符串数据),因为它是不可变的。如果您执行可变操作,例如value = [newValue uppercaseString],则它应该将这些位复制到value中,并且value的保留计数会增加。
关于ios - objective-c NSString *属性保留计数奇数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/403112/