创建文件并保存对象

时间:2012-07-02 23:32:01

标签: iphone objective-c ios cocoa-touch

为什么当你调用这个方法(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];
}

1 个答案:

答案 0 :(得分:0)

我认为问题在于您要编写的字典的内容。 您正在将object添加到字典中。 该对象必须只包含类型的成员:NSArray,NSDictionary,NSString,NSDate,NSData和NSNumber。如果你的对象包含一个int或float,或者除了这些之外的任何东西,它就不会写。

您可以阅读更多here