Kochan(第1版)中的“Objective C”编程使用以下代码(见第342-344页)来解释initWithString比stringWithString更好,因为AddressCard类将拥有名称变量内容.此外,我没有收到任何错误,使用stringWithString方法重复调用setName版本. TIA!
- //header file has appropriate declarations but not included here:
- #import "AddressCard.h"
- @implementation AddressCard;
- -(NSString *) name
- {
- return name;
- }
- //Recommended code:
- -(void) setName: (NSString *) theName
- {
- [name release]
- name = [[NSString alloc] initWthString: theName];
- }
- //Incorrect code according to Kochan:
- -(void) setName: (NSString *) theName
- {
- [name release]
- name = [NSString stringWthString: theName];
- }
- //rest of class implementation code snipped
- @end
解决方法
What I don’t understand is when would I use the stringWithString method since any local variable assigned that way would have it’s memory “owned” by NSString instead of the local class.
什么?没有.
规则很简单:
>由alloc,copy,copyWithZone或new返回的任何对象的保留计数为1.
>保留增加接收对象的保留计数.
释放减少接收对象的保留计数.
> autorelease告诉当前自动释放池发送接收对象释放消息“稍后”.
>任何在名称中没有“新”或“复制”的工厂方法(例如,stringWithString :)返回一个代表您自动释放的对象.
或者,消化了一点:
>任何名称包含copy,alloc,retain或new的方法返回您拥有的对象.
>任何方法不返回一个你不拥有的对象.
拥有一个对象,保留它.
setName的错误实现:您显示的是不正确的,因为它将自动释放的对象存储在实例变量中,当您意味着拥有对象时.您应该保留它,或者在这种情况下复制它.一种方法是简单地使用alloc和initWithString:,如你所显示的正确的例子;另一种方式是复制.
The Memory Management Programming Guide for Cocoa explains everything.每个Cocoa或Cocoa Touch程序员都应该不时读取或重新读取它.