Setting Default Values For NSString Properties

匆匆过客 提交于 2019-12-25 03:15:46

问题


I am trying to determine the recommended way to set default values for NSString properties.

I understand it is not safe to use accessor methods in a class's init and dealloc methods. I often have string constants that I would like to assign default values. What is the recommend way to do this (considering the iVar will be released in the dealloc method)?

For example I understand the following is unsafe:

@property (nonatomic, copy) NSString *identifier;
....

- (id) init
{ 
    self = [super initWithLayer:displayLayer];

    if (self != nil)
    {
        self.identifier = @"fireSpell01";
    }

    return self;
}

Is it ok, or recommend to do this:

identifier = [@"fireSpell01" retain];

Or must I do this:

identifier = [[NSString stringWithString:@"fireSpell01"] retain];

回答1:


Just do this:

identifier = @"fireSpell01";

There's no need to retain the string. String constants exist for the lifetime of the program and never need to be retained or released. Doing [[NSString stringWithString:@"fireSpell01"] retain] just creates an unnecessary copy and is pointless.

What you want to avoid is using the property setters in the init and dealloc methods. Because setters could potentially have side effects that depend on certain state values, you don't want to call them on partially constructed/partially destroyed objects. It is much better just to assign directly to the ivars and skip the setters during init.



来源:https://stackoverflow.com/questions/4264031/setting-default-values-for-nsstring-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!