2014年7月17日 星期四

Core Data 基本操作


查詢
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"GoToBedTime" inManagedObjectContext:self.managedObjectContext];
NSSortDescriptor *sortByDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSArray *sortArray = [[NSArray alloc] initWithObjects:sortByDate, nil];
fetchRequest.sortDescriptors = sortArray;
fetchRequest.entity = entity;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
GoToBedTime *goToBedTime = [array objectAtIndex:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
cell.detailTextLabel.text = [formatter stringFromDate:goToBedTime.date];

原本
WakeUpTime *wakeUpTime = [array objectAtIndex:0];
wakeUpTime.timing
優化
[[array objectAtIndex:0] timing]

handle the error
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; //沒有資料會取得零筆資料但不會有error
if (error) {
     //handle the error
}

相關範例
https://www.facebook.com/groups/iostw/permalink/969502549743761/