我在嵌套 NSDictionary 中保留数据时遇到问题。或者 NSMutableDictionary 是否可以使这项工作正常进行?你看一下,我会尽力解释的。
我的 .h 文件如下所示:
@interface MyViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
{
NSDictionary *fullData;
IBOutlet UITableView *tableView;
}
@property (nonatomic, retain) NSDictionary *fullData;
@property (nonatomic, retain) UITableView *tableView;
@end
我在 viewDidLoad 中设置了初始化
- (void)viewDidLoad {
...
fullData = [NSDictionary dictionaryWithContentsOfURL:url];
[fullData retain];
[super viewDidLoad];
}
当我尝试将其插入到 UITableViewCells 中时,无论我需要做什么,即使我执行一个在此处打印 fullData 的 NSLog,所有数据都会显示出来,效果很好。 像这样:
2010-11-24 14:49:53.334 MyApp[25543:40b] {
items = (
{
id = 5;
localId = 1;
name = "A name1";
},
{
id = 8;
localId = 3;
name = "A name2";
},
{
id = 9;
localId = 4;
name = "A name3";
},
{
id = 10;
localId = 5;
name = "A name4";
},
{
id = 11;
localId = 6;
name = "A name5";
}
);
results = 5;
}
虽然这工作得很好,但我想将完整数据保留在我的其他事件中,例如 didSelectRowAtIndexPath。首先,我必须保留 ,而且如果我这样做,只会保留第一级数据。字典项只会指向一些不存在的内存。
所以我尝试:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Data: %@", fullData);
}
有时会返回这样的结果:
2010-11-24 14:44:28.288 MyApp[25493:40b] Data: {
items = (
"<_NSIndexPathUniqueTreeNode: 0x9d2a820>",
"<CALayer: 0x9d27980>",
"<CALayer: 0x9d2bc30>",
"<CALayer: 0x9d29830>",
"<CALayer: 0x9d299e0>"
);
results = 5;
}
似乎保留了一些值,但项目内的数据无法访问。对我来说,将数据存储到本地文件然后再次访问它是否更好,或者应该可以保留完整的字典吗?
我尝试添加 [[fullData objectForKey:@"items"] keep];
我对此还很陌生,因此我需要帮助以使我的代码也遵循最佳实践。我尝试了很多解决方案,也看了苹果和其他地方的几部电影。我就是解决不了。这可能很简单,但我不知道在哪里看。
谢谢。
抱歉,这个问题是我自己解决的 我没有包含此功能:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Retain count: %i", [fullData retainCount]);
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:@"cell"];
// create a cell
if( cell == nil )
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"cell"];
}
// fill it with content
NSArray *current = [[fullData objectForKey:@"items"] objectAtIndex:indexPath.row];
NSString *rowLabel = [NSString stringWithFormat:@"%@, %@",[current valueForKey:@"localId"], [current valueForKey:@"name"]];
cell.textLabel.text = rowLabel;
[current release];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// return it
return cell;
}
问题是我释放了表中每一行的当前变量。这应该是因为变量current中的实例不是副本,而是真正的引用。
无论如何,谢谢。
最佳答案
fullData = [NSDictionary dictionaryWithContentsOfURL:url];
自动发布。您不应该保留
它。使用这个:
self.fullData = [[NSDictionary alloc] initWithContentsOfURL:url];
而且我认为您现在不需要为了您的目的而保留
它。仅当您需要在 MyViewController
发布后访问它时。
您要发布UITableView
吗?它可能会遍历并释放 NSDictionary 中的单元格。
没有更多代码,我不知道。
关于iPhone dev,NSDictionary如何保留完整的Dict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267653/