MrDatabase
MrDatabase

Reputation: 44455

What's the easiest way to persist data in an iPhone app?

I want to persist a very simple string. For example "abc". What's the easiest way to do this? I don't want to use a SqlLite database.

Upvotes: 5

Views: 1298

Answers (2)

user81038
user81038

Reputation:

If it is just one single string NSUserDefaults is probably the easiest way.

// write
[[NSUserDefaults standardUserDefaults] setObject:@"abc" forKey:@"MY_PERSISTENT_KEY"];

// read
NSString *abc = [[NSUserDefaults standardUserDefaults] valueForKey:@"MY_PERSISTENT_KEY"];

Upvotes: 18

jessecurry
jessecurry

Reputation: 22116

You can make your objects conform to NSCoding, then write them to a file using an NSKeyedArchiver.

NSString* path = [self pathForDataFile];
NSMutableDictionary* rootObject = [NSMutableDictionary dictionary];
[rootObject setValue: someObject forKey: @"SomeObject"];

// Commit data to file
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];

Upvotes: 0

Related Questions