Iphone NSMutable字符串“;“超出范围”;

Iphone NSMutable字符串“;“超出范围”;,iphone,objective-c,nsmutablestring,Iphone,Objective C,Nsmutablestring,我的viewController(UITableViewController.h文件的子类)中定义了两个NSMutableString对象: 它们是: @property (nonatomic, retain) NSMutableString *firstName; @property (nonatomic, retain) NSMutableString *lastName; 我在.m文件中合成了它们 在我的viewDidLoad方法中-我将它们设置为空字符串: firstName = [N

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

它们是:

@property (nonatomic, retain) NSMutableString *firstName;
@property (nonatomic, retain) NSMutableString *lastName;
我在.m文件中合成了它们

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

firstName = [NSMutableString stringWithString:@""];
lastName = [NSMutableString stringWithString:@""];
firstName和lastName可由用户更改。在我的cellForRowAtIndexPath方法中,我试图显示以下字符串的内容:

cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
但这会导致应用程序在显示视图控制器时崩溃。使用调试器,firstName和lastName似乎都“超出范围”或不存在。我不熟悉Xcode,但调试器似乎在objc_msgSend停止


我做错了什么?

养成将
self.variableName
放在。。。不要使用
stringwithstring
尝试使用
initWithString
…希望它能解决问题…顺便说一句,您已经很好地解释了这个问题…

您的单元格在初始化前正在加载和访问firstName和lastName。viewDidLoad太迟了,请尝试从NIB或viewWillLoad或iPhone上的任何内容唤醒。问题是您需要执行以下操作:

self.firstName = ...
self.lastName = ...
这将调用自动生成的setter方法,该方法将保留这些值。通过直接赋值,您就绕过了setter,一旦当前的autorelease池被耗尽,这两个变量就会有悬空指针。

您不能使用:

firstName = [NSMutableString stringWithString:@""];
因为它将在
viewDidLoad
执行完成后立即解除分配

尝试:

或:


不要忘记在
dealloc
消息中发布
firstName
lastName

您使用了什么单元格样式

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

也许这会对您有所帮助

那么:NSMutableString*firstName;NSMutableString*lastName;在文件级、类级或方法中定义?仅供参考,您添加objective-c标记BTW是正确的,因为这绝对是“经典的”objective-c。这将使值为nil,这不会给出预期的字符串,但也不会崩溃。“超出范围”不是nil,这意味着编译器还没有为相关变量分配任何值,无论是否为nil。
firstName = [[NSMutableString alloc] initWithString:@""];
[self setFirstName:[NSMutableString stringWithString:@""]];
if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                 reuseIdentifier:BasicCellIdentifier] autorelease];
}