NSKeyedUnarchiver unarchiveObjectWithFile: returns nil in init: method

前端 未结 2 1772
野性不改
野性不改 2021-01-04 23:22

Update: This works if I call archiveRootObject: from applicationDidFinishLaunching:. If I call it from the init: method of a singleton class, it returns nil.

2条回答
  •  生来不讨喜
    2021-01-04 23:27

    I've meet the same trouble in Xcode 4.1 with ARC support:

    BOOL isFileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    NSAssert(isFileExist, @"filePath does not exist");
    NSKeyedUnarchiver* coder =
        [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; // nil
    NSData* data = [[NSFileManager defaultManager] contentsAtPath:filePath];
    coder = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // nil
    coder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; // OK!!!
    

    It seems to be a bug in cocoa-touch.

    Edit:

    It is intended to behave like this and is not a bug. But I agree that the naming easily leads to mistakes.

    [[NSKeyedUnarchiver alloc] initForReadingWithData:] returns a NSKeyedUnarchiver instance.

    [NSKeyedUnarchiver unarchiveObjectWithData:] returns the root object. It is a conviencen method for:

    NSKeyedUnarchiver *coder = [[self alloc] initForReadingWithData:arg2];
    id object = [coder decodeObjectForKey:@"root"];
    

提交回复
热议问题