objective-c – 在NSString中的stringWithString和initWithStrin
我明白任何init …方法初始化一个新的对象,NSString stringWithString将一个参数字符串的副本作为一个新的对象.我也明白,作为对象的所有者,我可以控制我分配的任何对象的释放/释放.我不明白的是什么时候使用stringWithString方法,因为任何以这种方式分配的本地变量将使其由NSString而不是本地类拥有它的内存.
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 解决方法
什么?没有. 规则很简单: >由alloc,copy,copyWithZone或new返回的任何对象的保留计数为1. 或者,消化了一点: >任何名称包含copy,alloc,retain或new的方法返回您拥有的对象. setName的错误实现:您显示的是不正确的,因为它将自动释放的对象存储在实例变量中,当您意味着拥有对象时.您应该保留它,或者在这种情况下复制它.一种方法是简单地使用alloc和initWithString:,如你所显示的正确的例子;另一种方式是复制. The Memory Management Programming Guide for Cocoa explains everything.每个Cocoa或Cocoa Touch程序员都应该不时读取或重新读取它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |