Xcode - 过滤NSFetchRequest并选择每个对象

时间:2012-12-07 22:37:55

标签: xcode ios6 nsfetchrequest

我正在尝试过滤fetchRequest。

我正处于将结果加载到NSArray的位置。

但是,我需要解析数组以提取单个项目 - 现在,它们看起来好像是一个对象。

我用来达到这一点的代码是:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:moc];

[request setEntity:entity];


    // Order the events by name.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

    [request setSortDescriptors:@[sortDescriptor]];

    // Execute the fetch -- create a mutable copy of the result.
    NSError *error = nil;
    NSArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];

    if (categories == nil) {
        NSLog(@"bugger");
    }

    NSObject *value = nil;
    value = [categories valueForKeyPath:@"name"];

结果如下:

 value = (
)

[DetailViewController loadPickerArray]
[AppDelegate loadPickerArray]
 value = (
    "Cat Two",
    "Cat Three",
    "Cat One",
    "Cat Four"
)

此外,请注意,第一次运行,没有结果。大约50%的时间我得到了这个。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用多种方法过滤数据。

首选方法是为搜索使用谓词。这将为您提供最佳表现。

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:moc];

[request setEntity:entity];

// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[CD] %@", @"Cat"]; //This will return all objects that contain 'cat' in their name property.

[request setPredicate:predicate];
[request setSortDescriptors:@[sortDescriptor]];

// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [moc executeFetchRequest:request error:&error];

if (categories == nil) {
    NSLog(@"bugger");
}

//Here you have the objects you want in categories.

for(Category *category in categories)
{
    NSLog(@"Category name: %@", category.name);
}

如果您希望使用数组进行过滤,也可以使用以下内容:

NSMutableArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];

[categories filterUsingPredicate:[NSPredicate predicateWithFormat:[NSPredicate predicateWithFormat:@"name CONTAINS[CD] %@", @"Cat"]]

//Now, the only objects left in categories will be the ones with "cat" in their name property.

我建议阅读Predicates Programming Guide,因为谓词非常强大,而且在商店中过滤结果效率更高。