CoreData以前沒用過,最近試用了一下,感覺省了好多的代碼,很方便。當然,也只是會使用。
Dog *dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:self.managedObjectContext]; [dog setName:@"花花"]; [dog setAge:@(1)]; [dog setSex:@(0)];保存
NSError *error = nil; BOOL isSave = [self.managedObjectContext save:&error]; if (!isSave) { NSLog(@"error:%@,%@",error,[error userInfo]); } else{ NSLog(@"保存成功"); }
@property (strong, nonatomic) NSMutableArray *dataArray;
//創建取回數據請求 NSFetchRequest *request = [[NSFetchRequest alloc] init]; //設置要檢索哪種類型的實體對象 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog"inManagedObjectContext:self.managedObjectContext]; //設置請求實體 [request setEntity:entity]; //指定對結果的排序方式 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"ascending:NO]; NSArray *sortDescriptions = [[NSArray alloc]initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptions]; NSError *error = nil; //執行獲取數據請求,返回數組 NSMutableArray *mutableFetchResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResult == nil) { NSLog(@"Error: %@,%@",error,[error userInfo]); } self.dataArray = mutableFetchResult; for (Dog *dog in self.dataArray) { NSLog(@"age:%@---sex:%@---name:%@",dog.age,dog.sex,dog.name); }
[dog setName:@"哮天犬"]; NSError *error; BOOL isUpdateSuccess = [self.managedObjectContext save:&error]; if (!isUpdateSuccess) { NSLog(@"error:%@,%@",error,[error userInfo]); } else{ NSLog(@"更新成功!"); }
[self.managedObjectContext deleteObject:dog]; [self.dataArray removeObject:dog]; NSError *error; if (![self.managedObjectContext save:&error]) { NSLog(@"Error:%@,%@",error,[error userInfo]); } else{ NSLog(@"刪除成功!"); }