1

我正在使用 NSMutableString_s 的内容设置标签的文本,这些 NSMutableString_s 是 NSMutableDictionray 的对象......当我加载页面两次时所有事情都正常工作的问题(所以我推,在我弹出之后......)和第三次推送时,程序无法读取 NSMutableDictionary 的 NSMutableString_s 之一的内容。所以当它转到设置 UILabel 值的步骤时,它没有找到值...

有出现异常的代码:

- (void)viewDidLoad{
    [super viewDidLoad];
    NSMutableDictionary *item=[days objectAtIndex:0];
    NSString *title1=[item objectForKey:@"week_day"];
    name1.text=title1;
    [title1 release];
4

2 回答 2

1

你不应该释放title1- 你不拥有返回的字符串-objectForKey:,也没有通过保留它来获得所有权。
我建议通读Cocoa 内存管理指南以防止将来出现这种情况。

假设这text是一个retain属性:对于可变字符串,您应该分配字符串的副本以避免它们在您之下被更改:

NSString *title1 = [[item objectForKey:@"week_day"] copy];
name1.text = title1;
[title1 release]; // copy means taking ownership, so release

以下是您发布的代码可能发生的情况的简化示例:

// entering -viewDidLoad the first time:
NSString *title1=[item objectForKey:@"week_day"];
// lets assume that the strings retain count is 1 here
name1.text=title1;
// setter retains, retain count now 2
[title1 release];
// retain count now 1

// entering -viewDidLoad the second time:
NSString *title1=[item objectForKey:@"week_day"];
// assuming nothing else did retain it, strings retain count is still 1
name1.text=title1;
// you assigned the same object, retain count still 1
[title1 release];
// strings retain count now 0 - will be deallocated :(
于 2010-06-04T09:57:39.743 回答
0

谢谢大家,现在当我用中间变量逃避转换时它工作正常,但我不明白为什么它适用于之前的两个“推动”动作!!!

name1.text=[[days objectAtIndex:0] objectForKey:@"week_day"];
于 2010-06-04T10:43:21.100 回答