Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS store just a little bit of data

I was wondering if there is a way to store small amounts of data, without going to a full-blown core-data API. I just need to store 6 'double' values somewhere... What's the best approach for that?

Thanks, Alex.

like image 559
geekyaleks Avatar asked Sep 14 '11 13:09

geekyaleks


3 Answers

Core Data is just one way to store data, and it only makes sense when you need the things that it does. Here are five good options for storing your data:

  • Use NSUserDefaults. (Dead simple.)

  • Store the data in an appropriate structure (say, NSDictionary) and store it as a property list. (Pretty darn easy.)

  • Store the data in a class of your own design that implements NSCoding, and then write an instance of that class to a file using NSKeyedArchiver. (Works well for storing entire object graphs; this is basically what IB does. It might take an hour or two for the light to come on, but once you understand it this is a very nice way to read and write objects.)

  • Use Cocoa Touch's file system API, notably NSFileHandle and NSFileManager. (Conceptually simple if you've ever worked with a file system before. Puts you in complete control.)

  • Use the regular old POSIX file system API. (Best for existing Unix code, or code that you also want to compile on other platforms.)

Before you jump into any of those, read Apple's Archives and Serializations Programming Guide, User Defaults Programming Topics, and File System Programming Guide.

like image 193
Caleb Avatar answered Nov 13 '22 19:11

Caleb


You can use NSUserDefaults to accomplish that (http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html).

-(void)saveToUserDefaults:(NSString*)myString
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"Prefs"];
        [standardUserDefaults synchronize];
    }
}

-(NSString*)retrieveFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *val = nil;

    if (standardUserDefaults) 
        val = [standardUserDefaults objectForKey:@"Prefs"];

    return val;
}
like image 5
lluismontero Avatar answered Nov 13 '22 20:11

lluismontero


The easiest way to store small amounts of data without using some of the larger API's is the NSUserDefaults class. It's really easy to set up and use.

like image 4
Joe Avatar answered Nov 13 '22 20:11

Joe