How to add and retrieve data from NSDictionary inside a view controller

I'm trying to cache some images in a view controller using NSDictionary, but I'm not very lucky.

for starters, my .h looks like this

... NSDictionary *images; } @property (nonatomic, retain) NSDictionary *images; 

and in my .m I am synchronizing the property and trying to add the image as follows:

 [self.images setValue:img forKey:@"happy"]; 

and then I try to capture the image with the key

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

But every time I have an NSLog dictionary, it is null. If I have a @synthesize property, should I be ready to get out of the box? or didn’t I add this to the dictionary correctly?

Thank you in advance

+4
source share
1 answer

Synthesis does not instantiate the variable, so you still need to highlight + init at some point.

But if you want to add objects to the dictionary after creating it, you need to use NSMutableDictionary .

Then add + init to viewDidLoad using something like:

 self.images = [[[NSMutableDictionary alloc] initWithCapacity:10] autorelease]; 

Then, to set the value, use setObject:forKey: (not setValue:forKey: :

 [images setObject:img forKey:@"happy"]; 

Remember to free the dictionary in dealloc.

+5
source

Source: https://habr.com/ru/post/1340503/


All Articles