简体   繁体   English

创建文件并在其中保存对象

[英]Creating Files And Saving Objects In Them

Why when you call this method (saveObject: (id)object forKey: (NSString *) key), will a file not get created??? 为什么当您调用此方法(saveObject:(id)object forKey:(NSString *)键)时,无法创建文件???

When I call it filePath is equal to nil so the (-(void) setFilePath: (NSString *)fileName) method will get called... 当我调用它时,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];
}

I think the problem is with the contents of the dictionary you are intending to write. 我认为问题在于您打算编写的字典的内容。 You are adding object to your dictionary. 您正在将object添加到字典中。 That object must only contain members of types:NSArray , NSDictionary , NSString , NSDate, NSData and NSNumber. 该对象只能包含以下类型的成员:NSArray,NSDictionary,NSString,NSDate,NSData和NSNumber。 If your object contains a int or float , or anything other than these , it won't write. 如果您的对象包含一个int或float或除这些以外的其他任何东西,它将不会写入。

You can read more here 你可以在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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