如何设置提取请求以仅从具有一个特定值的实体属性中提取数据?这是我之前使用过的基本代码。
-(void)fetchResults
{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:self.entityDescription.name];
NSString *cacheName = [self.entityDescription.name stringByAppendingString:@"Cache"];
// predicate code
if (self.predicate != nil) {
[fetchRequest setPredicate:self.predicate];
}
// end of predicate code
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:cacheName];
BOOL success;
NSError *error;
success = [self.fetchedResultsController performFetch:&error];
if (!success)
{
NSLog(@"%@", [error localizedDescription]);
}
}
我一直在看这个页面:http://bit.ly/KevYwR http://bit.ly/KevYwR这是正确的方向吗?
我需要使用吗NSPredicate
或者我可以不用吗?
感谢您的帮助,指出正确的方向等等。
设置一个NSFetchRequest
相当于SQL语言中的SELECT语句。
这是一个简单的例子:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// error handling code
数组results
包含 sqlite 文件中包含的所有托管对象。如果您想获取特定对象(或更多对象),您需要在该请求中使用谓词。例如:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %@", @"Some Value"];
[request setPredicate:predicate];
在这种情况下results
包含属性等于的对象Some Value
。设置谓词相当于在 SQL 语句中放置 WHERE 子句。
Note
我认为该实体的名称是EntityName
它的属性称为attribute
这是字符串类型。
有关更多信息,我建议您阅读 Core Data 编程指南和NSFecthRequest
类参考。
http://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html http://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/NSFetchRequest.html https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/NSFetchRequest.html
希望能帮助到你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)