coredata一直很少用,一直用的sqlite,今天就总结一下好用的CoreData,毕竟是苹果的开发者,咱就使用原生的吧.模仿别人的写一遍,熟悉一下操作
1。按照 UserDefault模式操作
NSManagedObjectContext *context = [selfmanagedObjectContext];
//根据实体名称,创建一个实体实例
NSManagedObject *failedBankInfo = [NSEntityDescriptioninsertNewObjectForEntityForName:@"FailedBankInfo"inManagedObjectContext:context];
//赋值
[failedBankInfo setValue:@"Test Bank1"forKey:@"name"];
[failedBankInfo setValue:@"Testvile"forKey:@"City"];
[failedBankInfo setValue:@"Testland"forKey:@"state"];
NSManagedObject *failedBankDetails = [NSEntityDescriptioninsertNewObjectForEntityForName:@"FailedBankDetails"inManagedObjectContext:context];
[failedBankDetails setValue:[NSDatedate] forKey:@"closeDate"];
[failedBankDetails setValue:[NSDatedate] forKey:@"updateDate"];
[failedBankDetails setValue:[NSNumbernumberWithInt:12345] forKey:@"zip"];
[failedBankDetails setValue:failedBankInfo forKey:@"info"];
[failedBankInfo setValue:failedBankDetails forKey:@"details" ];
NSError *error;
//保存数据
if (![context save:&error]) {
NSLog(@"%@",error.localizedDescription);
}
2.按照类的实例方式赋值
AppDelegate * delegate = [NSApplicationsharedApplication].delegate;
// 获取上下文
NSManagedObjectContext * context = [delegate managedObjectContext];
NSFetchRequest * fetchRequest = [[NSFetchRequestalloc] init];
// 根据名称获取实体
NSEntityDescription * entity = [NSEntityDescriptionentityForName:@"FailedBankInfo"inManagedObjectContext:context];
// fetch设置实体
[fetchRequest setEntity:entity];
// fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"FailedBankInfo"];//可根据entity名称获取fetch
NSError * error;
// 在context中根据 fetch获取实体集
NSArray *fetchObjects = [context executeFetchRequest:fetchRequest error:&error];
// 遍历实体集
for (NSManagedObject *info in fetchObjects) {
NSLog(@"%@",[info valueForKey:@"name"]);
NSManagedObject * details = [info valueForKey:@"details"];
NSLog(@"Zip %@",[details valueForKey:@"zip"]);
}
从1.2两种方式看出,iOS的CoreData对数据的操作还是很方便的,省去了很大一部分sql语句,对于手机端开发人员省去了很多时间去学习SQL的东西,而去更加关注应用的细节开发