我是iOS开发的新出价。我正在使用NSManagedObject of Core Data来执行Insert和Fetch操作。它工作得很好。但问题是,我想从表中只获取一些选定的记录(在MySQL中的条件)。 对于例如"从city =' Pune'"; 我找到了NSPredicate来获取过滤后的数据。但它提供了数组中的所有数据,而不仅仅是所选数据。对于例如如果以上查询的结果是:
Anu
然后NSPredicate结果将给出:
fname = Anu
lname = Padhye
city = Pune
id = 3
有没有办法只在iOS Objective-c中获取所选的记录?以下是我用于NSManagedObject的代码片段:
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"User"];
valueData = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p=[NSPredicate predicateWithFormat:@"id == %d", 3];
[fetch setPredicate:p];
//... add sorts if you want them
NSError *fetchError;
NSArray *fetchedProducts=[valueData filteredArrayUsingPredicate:p];
答案 0 :(得分:15)
试试这个:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"User"];
request.predicate = [NSPredicate predicateWithFormat:@"city == %@ && id == %d", @"Pune", 3];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]];
NSArray *results = [managedObjectContext executeFetchRequest:request error:nil];
结果数组现在应包含所有将Pune作为其城市且ID为3的记录。