1. User Defaults:
This is probably the easiest and simplest way to save data in iphone. You can save the plist objects ie NSData, NSString, NSArray, NSNumber, NSDate and NSDictionary using user defaults. Other data types like floats, doubles, integers, booleans can also be saved using user defaults. Lets see some examples.Saving:
[[NSUserDefaults standardUserDefaults] setInteger:5 forKey:@"number"];
[[NSUserDefaults standardUserDefaults] setObject:@"hello" forKey:@"string"];
Retrieving:
NSInteger i = [[NSUserDefaults standardUserDefaults] integerForKey:@"number"];
NSString *s = [[NSUserDefaults standardUserDefaults] objectForKey:@"string"];
2. Files:
Data can also be saved in files using file manager. The following code shows an example of how an array is saved in a file named file.plist in the document directory and retreived later. //save data
-(void)saveData{
NSString *path = [(NSString *) [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.plist"];
NSArray *dataArray = [NSArray arrayWithObjects:@"item1",@"item2",nil];
[dataArray writeToFile:path atomically:YES];
}
//load data
- (void) loadData {
NSString *path = [(NSString *) [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath: path]) {
NSArray *dataArray= [[NSArray alloc] initWithContentsOfFile: path]; }
else {
NSLog(@"File not found");
}
}
3. SQLite Database:
If you need a full-blown database functionality, iphone provides you with the ability to use SQLite databases. You can have databases and write normal SQL queries. But ever since the introduction of core data in iphone OS 3, core data is much preferred than using raw SQLite. Internally core data also uses SQLite but it abstracts all the ugly details of underlying SQLite. If you are planning to use SQLite, I would suggest you to use core data instead. But if you are curious and want to learn how to use SQLite, there is a very nice 4 part tutorial at icodeblog. 4. Core Data:
As I said earlier, core data is an abstraction layer that sits on top of SQLite database. Majority of people prefer core data to using raw SQLite. But the learning curve is a more steep. You will find quite a lot of new concepts and terminologies in core data which can be quite intimidating at the beggining. Also it is a quite a big topic that entire books have been written on it. If you are really willing to master core data, then Core Data for iPhone
No comments:
Post a Comment