简体   繁体   中英

How should I save alarm app data?

I am making an alarm app for the iPhone, and was wondering what would be the best way to save my data. I have tried implementing CoreData but it doesn't work. I looked and found out that to use CoreData you have to tick a checkbox that says "Use CoreData for storage" when creating a new project in Xcode, which I didn't. Instead I created a View-Based Application. Can I still implement CoreData or should I use something else like plist or SQLite.

What I would do, just store the data in NSUserDefaults as Array of Dictionaries.

For example let's say you have:

NSDictionary *alarmOne = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:fireDateOne, labelOne, repeatIntervalOne, nil] forKeys:[NSArray arrayWithObjects:@"fireDate", @"label", @"repeatInterval"]];
NSDictionary *alarmTwo = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:fireDateTwo, labelTwo, repeatIntervalTwo, nil] forKeys:[NSArray arrayWithObjects:@"fireDate", @"label", @"repeatInterval"]];
NSArray *alarmsToBeSaved = [NSArray arrayWithObjects:alarmOne, alarmTwo, nil];
//save the alarms
[[NSUserDefaults standardUserDefaults] setObject:alarmsToBeSaved forKey:@"MyAlarms"];

//get alarms back from NSUserDefaults
NSArray *alarms = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAlarms"];
for (NSDictionary *alarm in alarms){
    NSLog(@"label of alarm: %@", [alarm objectForKey:@"label"]); //output alarm labels for example!
}

You could also save this Array to disk in the Documents directory of the app...

Core Data is usually better when you have large sets of data, that you want to pull out of the data base quickly (search) and better control of memory usage.

How to add a new alarm?

NSDictionary *alarmThree = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:fireDateThree, labelThree, repeatIntervalThree, nil] forKeys:[NSArray arrayWithObjects:@"fireDate", @"label", @"repeatInterval"]];

NSMutableArray *newAlarms = [NSMutableArray arrayWithObjects:[[NSUserDefaults standardUserDefaults] objectForKey:@"MyAlarms"]];
//add the new alarm Dict
[newAlarms addObject:alarmThree];
//save the array
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithArray:newAlarms] forKey:@"MyAlarms"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM