iphone - NSMutable 字符串 "Out of scope"

标签 iphone objective-c nsmutablestring

我在 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];

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

我做错了什么?

最佳答案

问题是你需要做:

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

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

关于iphone - NSMutable 字符串 "Out of scope",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2529354/

相关文章:

objective-c - 如何在 NSMutableString 中修剪 ""和 "\n"

ios - '尝试用 appendString :' error when parsing xml 改变不可变对象(immutable对象)

ios - iOS 7 中未调用 UIViewControllerTransitioningDelegate 方法

objective-c - const 全局字符串文字已损坏

iphone - NavigationBar 图层渐变效果不佳

ios - 编辑包含 NSFetchedResults 的 TableView

iphone - 如何将 NSString 插入 NSMutableString?

ios - 当只有键盘覆盖文本字段时向上移动 View

ios - 应用商店更新后 iPhone 5 崩溃

iphone - NSLocale currentLocale 总是返回 "en_US"而不是用户的当前语言