本文介绍了Objective C NSString *属性保留计数奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例类:

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吗?我缺少什么?

Shouldn't value have a retain count of 1? What am I missing?

感谢您的帮助。

推荐答案

引用一个不可变的字符串。赋值不需要复制值(字符串数据),因为它是不可变的。如果你做一个可变操作,例如value = [newValue uppercaseString],那么它应该将位复制到值,值的保留计数增加。

You've got a reference to an immutable string. Assignment doesn't need to copy the value (the string data) since it's immutable. If you do a mutable operation, like value = [newValue uppercaseString] then it should copy the bits into value, and value's retain count incremented.

这篇关于Objective C NSString *属性保留计数奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:51