由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'setObjectForKey:key不能为nil'

时间:2015-08-06 03:25:40

标签: ios objective-c nsexception

  

*由于未捕获的异常而终止应用   'NSInvalidArgumentException',原因:'* setObjectForKey:key不能   是零'***

我想我正在尝试将一个对象(nil)添加到字典中。我不知道怎么解决这个问题?

 @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

1 个答案:

答案 0 :(得分:0)

根据信息, setObjectForKey:key不能为nil ,因此您需要检查键和值,以确保在 self.navigationController?.navigationBar.barStyle = UIBarStyle.Black // I then set the color using: self.navigationController?.navigationBar.barTintColor = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0) // a lovely red self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // for titles, buttons, etc. let navigationTitleFont = UIFont(name: "Avenir", size: 20)! self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: navigationTitleFont] 之前它们都不是nil。

添加一些这样的保护:

setObject:ForKey:
相关问题