Smitha
Smitha

Reputation: 6134

How to store data for future use in iOS app

I want to store my data fetched from web service in a label. How can I do that? I have used :

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];   

But, its not getting updated with the value.

Upvotes: 0

Views: 576

Answers (1)

KerrM
KerrM

Reputation: 5240

You can save small amounts of data in NSUserDefaults like this:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *firstName = "Bob";
[defaults setObject:firstName forKey:@"firstName"];

[defaults synchronize];

And retrieve it like this:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *firstName = [defaults stringForKey:@"firstName"];

Read more about NSUserDefaults here

If you rather not use NSUserDefaults you can also use a property list like this:

NSArray *fruits = @[@"Apple", @"Mango", @"Pineapple", @"Plum", @"Apricot"];

NSString *filePathFruits = [documents stringByAppendingPathComponent:@"fruits.plist"];
[fruits writeToFile:filePathFruits atomically:YES];

NSDictionary *miscDictionary = @{@"anArray" : fruits, @"aNumber" : @12345, @"aBoolean" : @YES};

NSString *filePathDictionary = [documents stringByAppendingPathComponent:@"misc-dictionary.plist"];
[miscDictionary writeToFile:filePathDictionary atomically:YES];

NSArray *loadedFruits = [NSArray arrayWithContentsOfFile: filePathFruits];
NSLog(@"Fruits Array > %@", loadedFruits);

NSDictionary *loadedMiscDictionary = [NSDictionary dictionaryWithContentsOfFile: filePathDictionary];
NSLog(@"Misc Dictionary > %@", loadedMiscDictionary);

See this article to get more information on different ways to persistently store data in iOS.

Upvotes: 1

Related Questions