Patrick
Patrick

Reputation: 7185

Xcode 4.3 Saving user data

I am making my first major iPhone app and need some advice in saving user data. I looking to save a complex multidimensional array for example a list of contacts with both general information and lists of more data.

I have been searching the internet for a long time and found many tutorials but they seem to be a bit vague or unclear.

What are the best practises in saving such data? If anyone can direct me to a good tutorial that would be great. It is critical that updating the app does not lose the saved data.

Thanks

Upvotes: 0

Views: 3100

Answers (2)

webmastx
webmastx

Reputation: 683

Saving in plist file :

    // Copying the plist file
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    path = [[documentsDirectory stringByAppendingPathComponent:@"setting.plist"] retain]; 
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) 
    {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"setting" ofType:@"plist"]; 

        [fileManager copyItemAtPath:bundle toPath: path error:&error]; 
    }

    settings = [[NSMutableDictionary alloc]initWithContentsOfFile:path];

Usage :

NSString *keyname = [[settings allKeys]objectAtIndex:0];  // Or indexPath.row
[settings setObject:@"yes" forKey:keyname];  //Setting Value
[settings objectForKey:keyname]; //Getting Value

Upvotes: 1

James Webster
James Webster

Reputation: 32066

NSUserDefaults doesn't lose data when you update.

//Writing
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"anInt"];
[[NSUserDefaults standardUserDefaults] setDouble:1.2 forKey:@"aDouble"];
[[NSUserDefaults standardUserDefaults] setString:@"aString" forKey:@"aString"];
[[NSUserDefaults standardUserDefaults] synchronize];

//Reading:

int i = [[NSUserDefaults standardUserDefaults] integerForKey:@"anInt"]

Upvotes: 2

Related Questions