开发者

copying plist to document directory

开发者 https://www.devze.com 2023-04-12 02:21 出处:网络
How do I copy an existing plist I have in the app build to the Document directory? My plist is basically an array of dictionary, I have successfully copy the plist to the directory using the followin

How do I copy an existing plist I have in the app build to the Document directory?

My plist is basically an array of dictionary, I have successfully copy the plist to the directory using the following:

 BOOL success;
            NSError *error;

            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"States.plis开发者_StackOverflowt"];

            success = [fileManager fileExistsAtPath:filePath];
            if (success) return;

            NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];    
            success = [fileManager copyItemAtPath:path toPath:filePath error:&error];

            if (!success) {
                NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]);
            } 

However, when I try to access the NSDictionary it gives me:

CoreAnimation: ignoring exception: -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object

Why is this? I have to relaunch the app again and now I can change the dictionary stored in my array


This is the way I copy the *.plist file to documents folder. Hope this helps.

+ (NSString*) getPlistPath:(NSString*) filename{
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:filename];
}
+ (void) copyPlistFileToDocument{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [Utilities getPlistPath:@"AppStatus.plist"];
    if( ![fileManager fileExistsAtPath:dbPath])
    {
        NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"AppStatus" ofType:@"plist"];
            BOOL copyResult = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
            if(!copyResult)
                    NSAssert1(0, @"Failed to create writable plist file with message '%@'.", [error localizedDescription]);
    }

}


Just create a new pList in the documents directory, and set to the contents of the existing plist you have.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号