Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing objects in iOS for later use

My app is pulling in JSON data from our web service. In all instances up til now, the information would be retained in memory or just refreshed on the fly with no need to retain anything locally other than the login token used in the API. With one of the new features we are adding, we will be taking in a group of locations, 26 max, with long, lat, radius, and name.

I also need to add 1-2 fields to this data to create a larger object. So my question is, what would be the best way to store this type of data in the iOS filesystem? Currently I have been using the NSUserDefaults, but that seems sort of limited or ill advised for larger amounts of data. Maybe not.

This data will need to be retrieved, changed or edited, and resaved. All of this while still retaining the ability to pull any of those 26 objects. Thank you in advance for reading and helping out.

like image 539
Bill Burgess Avatar asked Aug 07 '11 12:08

Bill Burgess


2 Answers

For such a small amount of data (26 items) I suggest archiving.

Save to plist using NSKeyedArchiver/NSKeyedUnarchiver. Read your data from the delegate's didFinishLaunchingWithOptions, and listen for UIApplicationWillResignActiveNotification to save it.

A NSUserDefaults is a plist with features designed to store user preferences. It's often used instead a regular plist to save a couple of lines of code, which I think it's a bad idea because you get an additional complexity unrelated to your task.

If you want the login to be protected against someone stealing the device and performing forensics use the Keychain. You may want to use a wrapper and read some articles, comment if you are interested.

If you look for more features see Best way to store data on iphone but doesn't seem to be the case now.

Some code to get you started... Register to call save on app resign:

[[NSNotificationCenter defaultCenter]
        addObserver:self 
           selector:@selector(saveMyData) 
               name:UIApplicationWillResignActiveNotification 
             object:nil];

On each object of the graph/dictionary/whatever you want to archive implement NSCoding:

- (void)encodeWithCoder:(NSCoder*)coder {
    [coder encodeObject:myIvar forKey:kmyIvar];
}

- (id)initWithCoder:(NSCoder*)coder {
    if((self = [super initWithCoder:coder])) {
        self.myIvar = [[coder decodeObjectForKey:kmyIvar] retain];
    }
    return self;
}
like image 65
Jano Avatar answered Sep 18 '22 12:09

Jano


Check out this guide on core data. It's the best way to store data locally on your device. It's a native cocoa API and it is bindings compatible. Plus, you can choose whether to store data as XML, SQLite, and Binary.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

For anything remotely large, I would use this.

like image 27
Scott Harwell Avatar answered Sep 19 '22 12:09

Scott Harwell