我希望能更好地理解Cocoa中字符串的内存特性。 我正在使用的应用程序使用一个视图控制器和n个工具对象。视图控制器在程序的整个生命周期中生存,但工具对象被分配和释放。当在常量字符串和非常量字符串之间交替时,NSString的最佳分配
假设我有一个字符串toolName_并在我的实现中配置了传入的工具对象:如果对象没有工具名称,我想将toolName_ string设置为@“not set”。如果该工具有一个名称,我想将该字符串设置为该工具的名称。
我想知道存储传入的值到toolName_因为有时这将是一个分配的对象,有时这将是一个常量字符串的正确方法。
-(BOOL)setToolObject: ToolObject: obj{
ToolObject someObj = nil;
someObj = [[ToolObject alloc]initWithObject obj];
if(someObj != nil){
if(! [someObj.toolName isEqualToString: @""]){
self->toolName_ = Which method should I use given the above question?
The last instance may have been a constant string but may not have.
[self->toolName_ release] (can I send a release message to a constant
string without causing a problem?)
self->toolName = [[NSString alloc]initWithString:someObj.toolName];
OR
self->tool name = [NSString stringWithString: someObj.toolName];
This method is self releasing but I don't own it and I'm still not sure
what happens to the constant string if it existed. I think I read it's
not recommended to use this on member vars.
}else{
self->toolName_ = @"not set";
}
return YES;
}else{
return NO;
}
}
建议感激。
通常,'self>不用于访问Objective-C中的ivars。同样,具有返回值的setter也非常不典型。你通常希望限制setter/getter到可以用'@ property'表示的东西。 – bbum