NSMutable字符串"超出范围"

Gar*_*tet 2 iphone objective-c nsmutablestring

我有一个在我的viewController(UITableViewController的子类).h文件中定义的NSMutableString对象:

NSMutableString *firstName;
NSMutableString *lastName;
Run Code Online (Sandbox Code Playgroud)

它们是属性:

@property (nonatomic, retain) NSMutableString *firstName;
@property (nonatomic, retain) NSMutableString *lastName;
Run Code Online (Sandbox Code Playgroud)

我在.m文件中合成它们.

在我的viewDidLoad方法中 - 我将它们设置为空字符串:

firstName = [NSMutableString stringWithString:@""];
lastName = [NSMutableString stringWithString:@""];
Run Code Online (Sandbox Code Playgroud)

firstName和lastName可以由用户更改.在我的cellForRowAtIndexPath方法中,我正在尝试显示这些字符串的内容:

cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
Run Code Online (Sandbox Code Playgroud)

但这会导致应用程序在显示视图控制器后立即崩溃.使用调试器,似乎firstName和lastName都是"超出范围"或者它们不存在.我是Xcode的新手,但调试器似乎停在了objc_msgSend.

我究竟做错了什么?

smo*_*gan 6

问题是你需要这样做:

self.firstName = ...
self.lastName = ...
Run Code Online (Sandbox Code Playgroud)

这将调用自动生成的setter方法,这将保留值.通过直接分配,您绕过了setter,并且一旦当前自动释放池耗尽,两个变量将具有悬空指针.