我想要一些帮助以更好地理解 Cocoa 中字符串的内存特性。我正在使用的应用程序使用一个视图控制器和 n 个工具对象。视图控制器在程序的生命周期中存在,但工具对象被分配和释放。
假设我有一个字符串 toolName_ 并且在我的实现中我配置了传入的工具对象:如果对象没有工具名称,我想将 toolName_ 字符串设置为@“未设置”。如果工具有名称,我想将字符串设置为工具的名称。
我想知道将传入值存储到 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;
}
}
建议表示赞赏。