问题描述
我如何设置一个读取请求只与一个特定的值拉离实体的属性的数据?这是我以前所使用的基本code。
How do I setup a fetch request to only pull the data from an entity's attribute with one particular value? This is the basic code I've used before.
-(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]);
}
}
我一直在看这个页面:这是正确的方向?
我是否需要使用 NS predicate
或者我可以不用?
Do I need to use NSPredicate
or can I do without?
感谢您的帮助,在正确的方向点,等等。
Thanks for any help, point in the right direction, etc.
推荐答案
设置一个 NSFetchRequest
相当于SQL语言的SELECT statetement。
Setting up a NSFetchRequest
is equivalent to a SELECT statetement in SQL language.
下面一个简单的例子:
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
阵列结果
包含所有包含源码文件中的管理对象。如果你想抓住特定对象(或多个对象),你需要使用predicate这一请求。例如:
The array results
contains all the managed objects contained within the sqlite file. If you want to grab a specific object (or more objects) you need to use a predicate with that request. For example:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"attribute == %@", @"Some Value"];
[request setPredicate:predicate];
在这种情况下,结果
包含其中,属性等于某个值
的对象。设置predicate等于把在WHERE子句中的SQL语句。
In this case results
contains the objects where attribute is equal to Some Value
. Setting a predicate is equal to put the WHERE clause in a SQL statement.
注意
我假设实体的名称是实体名称
和它的属性被称为属性
这是字符串类型
I suppose that the name of the entity is EntityName
and its property is called attribute
which is of type string.
有关进一步信息,我建议你阅读核心数据编程指南和 NSFecthRequest
类引用。
For further info I suggest you to read the Core Data programming guide and NSFecthRequest
class reference.
-
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
希望它帮助。
这篇关于为获取== entity.attribute @&QUOT请求; someValue中"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!