简体   繁体   中英

reading a file using NSFileManager causing an error

I am getting the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:

The code that's causing the error is:

NSDictionary *dict = nil;
    @synchronized(self) {
        dict = [pendingDictionarySaves objectForKey:file];
    }
    if (dict) return dict;

    @synchronized(self) {
        dict = [savedDictionaries objectForKey:file];
    }
    if (dict) return dict;

    NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:file];

    NSError *error = nil;
    if ([[NSPropertyListSerialization class]
         respondsToSelector:@selector(propertyListWithData:options:format:error:)]) {
        return [NSPropertyListSerialization propertyListWithData:plistData
                                                         options:NSPropertyListImmutable
                                                          format:NULL
                                                           error:&error];
    }

Basically the reason is because the plistData is null. The filepath is:

/Users/aditya15417/Library/Application Support/iPhone Simulator/5.1/Applications/A355D003-668C-4B81-80DC-66C968FE57D3/Library/Caches/NewsfeedCache/?type=news

Here's how I initialize the path:

  NSString *path = [basePath stringByAppendingPathComponent:[streamURL uniqueFileName]];

    // Create the directories if needed
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
    }

    return path;

The question is how is it possible to get it to work without having to check if pListData is null?

Maybe you would be better off using +[NSData dataWithContentsOfFile:options:error:]. That method will at least give you an error if the read failed. Something like:

NSError *error = nil;
NSData *plistData = [NSData dataWithContentsOfFile:file options:0 error:&error];
if(!plistData) {
    NSLog(@"failed to read data: %@",error);
    return nil;
}

if ([[NSPropertyListSerialization class]
     respondsToSelector:@selector(propertyListWithData:options:format:error:)]) {
    return [NSPropertyListSerialization propertyListWithData:plistData
                                                     options:NSPropertyListImmutable
                                                      format:NULL
                                                       error:&error];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM