如何在视图控制器中添加和检索NSDictionary中的数据

Tor*_*ups 4 objective-c nsdictionary

我正在尝试使用NSDictionary在我的视图控制器中缓存一些图像,但我没有太多运气.

对于初学者我的.h看起来像这样

...
  NSDictionary *images;
}

@property (nonatomic, retain) NSDictionary *images;
Run Code Online (Sandbox Code Playgroud)

在我的.m我合成属性并尝试添加图像如下:

[self.images setValue:img forKey:@"happy"];
Run Code Online (Sandbox Code Playgroud)

后来我试图按键抓取图像

UIImage *image = [self.images objectForKey:@"happy"];
    if (!image) {
      NSLog(@"not cached");
    }else {
      NSLog(@"had cached img %@", image);
    }
Run Code Online (Sandbox Code Playgroud)

然而每次我NSLog字典它都是空的.如果我@synthesize属性我应该准备好开箱即用?或者我没有正确地将它添加到字典中?

先感谢您

小智 5

合成不会实例化变量,因此您仍需要在某个时刻分配+ init.

但是如果要在创建后将对象添加到字典中,则需要使用它NSMutableDictionary.

然后在viewDidLoad中使用以下内容对其进行alloc + init:

self.images = [[[NSMutableDictionary alloc] initWithCapacity:10] autorelease];
Run Code Online (Sandbox Code Playgroud)

然后设置一个值,使用setObject:forKey:(不setValue:forKey:):

[images setObject:img forKey:@"happy"];
Run Code Online (Sandbox Code Playgroud)

记得在dealloc中发布字典.