Save and Load Data - CoreData

被刻印的时光 ゝ 提交于 2019-12-01 07:38:16

To start you need a data model to reflect what you want to save, in this case, some text and a date. So:

DatedText{
    savedText:String
    dateSaved:Date
}

To create a new DatedText object (without a custom class) do:

NSManagedObject *newDatedText;
newDatedText=[NSEntityDescription insertNewObjectForEntityForName:@"DateText" inManagedObjectContext:theManagedObjectContext];
[newDatedText setValue:someText forKey:@"savedText"];
[newDatedText setValue:aDateObject forKey:@"dateSaved"];

NSError *saveError=nil;
[theManagedObjectContext save:&saveError];
if (saveError!=nil) {
    NSLog(@"[%@ saveContext] Error saving context: Error=%@,details=%@",[self class], saveError,saveError.userInfo);
}

To retrieve a DatedText object with a specific date you create a fetch like so:

NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
NSEntityDescription *testEntity=[NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.moc];
[fetch setEntity:testEntity]; 
NSPredicate *pred=[NSPredicate predicateWithFormat:@"dateSaved==%@", targetDate];
[fetch setPredicate:[NSArray arrayWithObject:pred]];

NSError *fetchError=nil;
NSArray *fetchedObjs=[theManagedObjectContext executeFetchRequest:theFetch error:&fetchError];
if (fetchError!=nil) {
    NSLog(@" fetchError=%@,details=%@",fetchError,fetchError.userInfo);
    return nil;
}

fetchedObjs will now contain an array of all DatedText objects with the same savedDate as targetDate.

Robin

There are lots of resources about Core Data, you could follow the following links to learn it. http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html Core Data Tutorial for iOS: this is really great, official document, easy to learn, with downloadable source. Any good guide about iPhone Core Data? Someone asked the same question before, you can take a look.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!