开发者

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 sto开发者_StackOverflowre 6 'double' values somewhere... What's the best approach for that?

Thanks, Alex.


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.


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜