我正在尝试在我的应用程序中使用Core Data。我想存储一个属性“totalKM”。
存储我的属性我使用这些行:
Model *event = (Model *)[NSEntityDescription insertNewObjectForEntityForName:@"Model" inManagedObjectContext:managedObjectContext];
int number = 4;
[event setTotalKM:[NSNumber numberWithDouble:number]];
读取我的属性我使用这些:
Model *event = (Model *)[NSEntityDescription insertNewObjectForEntityForName:@"Model" inManagedObjectContext:managedObjectContext];
NSNumber *number = [event totalKM];
我的属性“totalKM”始终是默认值,O。我也不例外。我错过了什么吗?
感谢。
答案 0 :(得分:2)
insertNewObjectForEntityForName
此方法用于将模型置于上下文中。
这是一个新对象。
正确的方法是:
设置新的
Model *event = (Model *)[NSEntityDescription insertNewObjectForEntityForName:@"Model" inManagedObjectContext:managedObjectContext];
int number = 4;
[event setTotalKM:[NSNumber numberWithDouble:number]];
//save change if need
NSError *error = nil;
if (![self.manageObjectContext save:&error]) {
NIDERROR(@"save managedContext error :%@",error);
}
获取对象进度
当你需要获得一个模型表格coredate.u需要2次获取使用获取
像这个圆顶一样NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Board"
inManagedObjectContext:self.manageObjectContext]];
//set fetch conditions
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"board_id == %@", aBoardID];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *results = [self.manageObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NIDERROR(@"fetch board error.\n board id: %@ \n error:%@", aBoardID, error);
return nil;
}
Model *model = results[0];
NSLog(@"%@",model.totalKM)