0

为什么当你调用这个方法(saveObject: (id)object forKey: (NSString *) key)时,文件不会被创建???

当我调用它时,filePath 等于 nil,因此 (-(void) setFilePath: (NSString *)fileName) 方法将被调用...

-(int) saveObject: (id)object forKey: (NSString *) key {
    //save object into file

    if(filePath == nil) {
        [self setFilePath:nil];
    }

    mainDict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    if(mainDict == nil) {
        mainDict = [[NSMutableDictionary alloc] init];
    }

    [mainDict setObject:object forKey:key];

    if(![mainDict writeToFile:filePath atomically:YES]) {
        if(object == nil) {
            return 3;
        }
        if(key == nil) {
            return 4;
        }
        return 2; //ERROR could not write object to file
    } else {
        if(shouldUseCache == YES) {
            cacheStatus = 2; //New Caches need to be updated
        }
        return 1; //SUCCESS object saved to file
    }

    //RETURN KEY's
    // *1 SUCCESS object saved to file
    // *2 ERROR could not write object to file
    // *3 ERROR object variable = nil
    // *4 ERROR key variable = nil
}

-(void) setFilePath: (NSString *)fileName {
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsDirectory = [paths objectAtIndex:0];
    if(fileName == nil) {
        fileName = @"savedObjects";
    }
    filePath = [NSString stringWithFormat:@"%@/%@.plist",documentsDirectory, fileName];
}
4

1 回答 1

0

我认为问题在于您打算编写的字典的内容。您正在添加object到您的字典中。该对象只能包含以下类型的成员:NSArray、NSDictionary、NSString、NSDate、NSData 和 NSNumber。如果您的对象包含 int 或 float 或这些以外的任何内容,则它不会写入。

你可以在这里阅读更多

于 2012-07-03T00:26:43.930 回答