Search code examples
iphoneurl-rewritingplistdocuments

PList Chicken/Egg Scenario


I want to read/write to cache.plist

If I want to read an existing premade plist file stored in the resources folder I can go:

path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent@"cache.plist"];
NSMutableDictionary *root = ...

But then I wish to read it from the iPhone.

Can't, the Resources folder is only readable.

So I need to use:

NSDocumentDirectory, NSUserDomain,YES

So how can I have my plist file preinstalled to the Document Directory location?

Thus meaning I don't have to mess around with untidy code copying the plist file over at startup. (Unless that's the only way).


Solution

  • The final product

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:@"Cache.plist"];
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *giveCachePath = [documentsDirectory stringByAppendingPathComponent:@"Cache.plist"];
    
    
    BOOL fileExists = [fileManager fileExistsAtPath:giveCachePath];
    
    if (fileExists) {
        NSLog(@"file Exists");
    }
    else {
        NSLog(@"Copying the file over");
        fileExists = [fileManager copyItemAtPath:finalPath toPath:giveCachePath error:&error];
    }
    
    NSLog(@"Confirming Copy:");
    
    BOOL filecopied = [fileManager fileExistsAtPath:giveCachePath];
    
    if (filecopied) {
        NSLog(@"Give Cache Plist File ready.");
    }
    else {
        NSLog(@"Cache plist not working.");
    }