使用parse下载图像会导致无法识别的选择器错误

man*_*dev 0 objective-c ios parse-platform ios6 pfquery

我正在尝试从Parse下载图像,当我完成从解析程序下载所有图像时我的程序崩溃并出现错误:

NSNull getDataInBackgroundWithBlock:progressBlock:]:发送到实例的无法识别的选择器.

我试过添加一些条件,如

if(![object objectForKey:@"goal_image"]) //If it is nil => exit
Run Code Online (Sandbox Code Playgroud)

但它仍在崩溃.这是我的代码:

        PFQuery *query = [PFQuery queryWithClassName:@"Goal"];

        [query getObjectInBackgroundWithId:[object objectId] block:^(PFObject *object, NSError *error) {

            if(!error)
            {
                PFFile * imageFile = [object objectForKey:@"goal_image"];
                if (imageFile) {

                    [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error2) {
                        if (!error2) {

                            NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Images/Goals/%@",[object objectId]]];
                            [data writeToFile:jpgPath atomically:YES];

                        }
                    } progressBlock:^(int percentDone) {
                        if (percentDone == 100) {
                            NSLog(@"Download Completed");
                        }

                    }];
                }
            }
        }];
Run Code Online (Sandbox Code Playgroud)

Gab*_*lla 5

TL;博士

你应该检查NSNull除了检查nil.

PFFile * imageFile = object[@"goal_image"]; // note the modern Obj-C syntax
if (imageFile && ![image isEqual:[NSNull null]]) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

说明

NSNull不同于nil,第一个是一个对象.

由于NSArray并且NSDictionary只保存对象,nil因此无法存储在此类容器中,这NSNull就是使用的原因,通常用于表示nullJSON响应中返回的值.

发送消息nil静默失败,而向NSNull单例发送无法识别的选择器将导致崩溃.

还要记住,如果在字典中找不到密钥,objectForKey:它将返回nil.