I am trying to determine the recommended way to set开发者_Go百科 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];
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
.
精彩评论