如何在视图控制器内的 NSDictionary 添加和检索数据
我正在尝试使用 NSDictionary 在视图控制器中缓存一些图像,但运气不佳。
对于初学者来说,我的 .h 看起来像这样
...
NSDictionary *images;
}
@property (nonatomic, retain) NSDictionary *images;
,在我的 .m 中,我合成属性并尝试添加图像,如下所示:
[self.images setValue:img forKey:@"happy"];
后来我尝试通过键抓取图像
UIImage *image = [self.images objectForKey:@"happy"];
if (!image) {
NSLog(@"not cached");
}else {
NSLog(@"had cached img %@", image);
}
但每次我 NSLog 字典时它都是空的。如果我 @synthesize 该属性我应该准备好开箱即用吗?或者我没有正确地将其添加到字典中?
先感谢您
I'm trying to cache some images in my view controller using NSDictionary but I'm not having much luck.
for starters my .h looks like this
...
NSDictionary *images;
}
@property (nonatomic, retain) NSDictionary *images;
and in my .m I synth the property and attempt to add the image as follows:
[self.images setValue:img forKey:@"happy"];
and later I attempt to grab the image by key
UIImage *image = [self.images objectForKey:@"happy"];
if (!image) {
NSLog(@"not cached");
}else {
NSLog(@"had cached img %@", image);
}
Yet each time I NSLog the dictionary it's null. If I @synthesize the property should I be ready to go out of the box? or did I not add this to the dictionary correctly?
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
综合不会实例化变量,因此您仍然需要在某个时候分配+初始化它。
但如果你想在创建字典后将对象添加到字典中,则需要使用
NSMutableDictionary
。然后在 viewDidLoad 中使用类似以下内容对其进行分配+初始化:
然后要设置值,请使用
setObject:forKey:
(而不是setValue:forKey:
):请记住在中释放字典解除分配。
Synthesizing doesn't instantiate the variable so you still need to alloc+init it at some point.
But if you want to add objects to a dictionary after creating it, you need to use
NSMutableDictionary
instead.Then alloc+init it in viewDidLoad using something like:
Then to set a value, use
setObject:forKey:
(notsetValue:forKey:
):Remember to release the dictionary in dealloc.