* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* setObjectForKey: key cannot be nil' ***
I think i am trying to add an object (which is nil) to dictionary for key. I DO NOT KNOW HOW TO SOLVE THIS?
@interface BNRImageStore ()
@property (nonatomic, strong) NSMutableDictionary *dictionary;
@end
@implementation BNRImageStore
+(instancetype)sharedStore{
static BNRImageStore *sharedStore;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedStore = [[self alloc]initPrivate];
});
return sharedStore;
}
-(instancetype)initPrivate {
self = [super init];
if (self) {
_dictionary = [[NSMutableDictionary alloc]init];
}
return self;
}
-(NSString*)imagePathForKey:(NSString*)key{
NSArray *documentDirectories =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentDirectory = [documentDirectories firstObject];
return [documentDirectory stringByAppendingPathComponent:key];
}
-(void)setImage:(UIImage*)image forKey:(NSString*)key{
self.dictionary[key] = image;
NSString *imagePath = [self imagePathForKey:key];
NSData *data = UIImageJPEGRepresentation(image, 0.5);
[data writeToFile:imagePath atomically:YES];
}
-(UIImage*)imageForKey:(NSString*)key{
UIImage *result = self.dictionary[key];
if (!result) {
NSString *imagePath = [self imagePathForKey:key];
result = [UIImage imageWithContentsOfFile:imagePath];
if (result) {
[ self.dictionary setObject:result forKey:key];
}
else {
NSLog(@"ERROR");
}
}
return result;
}
-(void)deleteImageForKey:(NSString*)key{
if (!key) {
return;
}
[self.dictionary removeObjectForKey:key];
NSString *imagePath = [self imagePathForKey:key];
[[NSFileManager defaultManager]removeItemAtPath:imagePath error:nil];
}
@end