我有一堆MySQL行,我从PHP脚本下载到iOS并保存到核心数据中。现在,我对核心数据相对较新。我如何从核心数据中获取其中一行以显示?如果这太模糊,我的情况就是这样:当用户点击iOS中的特定按钮时,我想根据用户显示特定结果,例如与较大列表中的用户位置匹配的城市名称城市名称。但是,我只需要一行。我只是希望了解这个过程和任何帮助,无论是教程还是具体的建议都将不胜感激!
答案 0 :(得分:1)
以下是使用对象的基础知识:
// Utility method to fetch objects
- (NSArray *)fetchEntity:(NSString *)entityName withPredicate:(NSPredicate *)predicate inContext:(NSManagedObjectContext *)moc
{
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc];
[request setEntity:entity];
[request setPredicate:predicate];
return [moc executeFetchRequest:request error:nil];
}
您可以像这样使用它来获取名称:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@",@"My product"]; // act as a filter
NSManagedObject *product = [[CoreDataUtils fetchEntity:@"Product" withPredicate:predicate inContext:self.moc] objectAtIndex:0];
NSLog(@"%@",[product objectForKey:@"name"]);
或者您可以设置如下名称:
[product setValue:@"New Product" forKey:@"name"];
编辑对象时不要忘记保存NSManagedObjectContext
[self managedObjectContext save:nil];
这里有一个很棒的教程:Core Data on iOS 5 Tutorial: Getting Started