开发者

Quick and dirty way to store NSStrings (or other data) from launch to launch?

I want to allow my user to store custom phrases, to be displayed in an editable UITableView.

What's a quick and dirty to store these strings?

I'm f开发者_运维问答airly new at iPhone development. I know about Core Data, but not how to use it. I would stay away form that just for this particular project if possible. Are PLIST files a possibility here?

Sample code is appreciated.


Use NSUserDefaults. There's some code over in this question.


If you want to use plists this is the quickest way (I think) to go. There are other ways to do it with NSCoding to encode your data to a file, but you would probably need a custom data model class, this is more suited to saving more random things that wouldn't fit into a prescribed data model. Also, as has been pointed out, NSUserDefaults is also an option

To save your work:

-(void)applicationWillTerminate:(NSNotification *)notification {
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *filePath = [documentsDirectory stringByAppendingString:@"info.plist"];
   NSMutableArray *array = [[NSMutableArray alloc] init];
// Add the objects you want to save to the array here ex: [array addObject:]
   [array writeToFile:filePath atomically:YES];
   [array release];  }

And to recover your saved file:

- (void)viewDidLoad {
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *filePath = [documentsDirectory stringByAppendingString:@"info.plist"];
   if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
       NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
    // Set your vaiables here in the order that you saved them ex. var = [array objectAtIndex:]
       [array release];
   }
   UIApplication *app = [UIApplication sharedApplication];
   [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(applicationWillTerminate:) 
                                             name:UIApplicationWillTerminateNotification 
                                           object:app];

    [super viewDidLoad];}

Basically, when your application is about to quit you create and array of the objects you want to save and write them to the file, and when you application starts again you read that file back into an array and assign your variables based on the order in which you saved them. Then you set it up so when your application sends its UIApplicationWillTerminateNotification it executes your code to save your (presumably) modified variables back into a file.


You probably want NSDefaults; check out the User Defaults Programming Topics guide.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜