2

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

NSMutableString *firstName;
NSMutableString *lastName;

它们是属性:

@property (nonatomic, retain) NSMutableString *firstName;
@property (nonatomic, retain) NSMutableString *lastName;

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

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

firstName = [NSMutableString stringWithString:@""];
lastName = [NSMutableString stringWithString:@""];

用户可以更改名字和姓氏。在我的 cellForRowAtIndexPath 方法中,我试图显示这些字符串的内容:

cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

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

我究竟做错了什么?

4

5 回答 5

6

问题是你需要做:

self.firstName = ...
self.lastName = ...

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

于 2010-03-27T13:11:08.310 回答
1

养成放置self.variableName...的习惯,而不是stringWithsString尝试使用initWithString...希望它能解决问题...顺便说一句,您已经很好地解释了这个问题...

于 2010-03-27T13:08:56.033 回答
0

您的单元格在初始化之前正在加载和访问 firstName 和 lastName。viewDidLoad 为时已晚,请尝试 awakeFromNib 或 viewWillLoad 或 iPhone 上的任何内容。

于 2010-03-27T13:10:20.537 回答
0

你不能使用:

firstName = [NSMutableString stringWithString:@""];

因为它会在viewDidLoad执行完成后立即释放。

尝试:

firstName = [[NSMutableString alloc] initWithString:@""];

或者:

[self setFirstName:[NSMutableString stringWithString:@""]];

并且不要忘记发布firstNamelastName发布dealloc消息。

于 2010-03-27T13:11:54.497 回答
0

你用的是什么单元格样式?

if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                 reuseIdentifier:BasicCellIdentifier] autorelease];
}

也许这会帮助你

于 2012-03-14T08:54:39.933 回答