0

我正在尝试过滤 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% 的时间能做到这一点。

谢谢你的帮助。

4

1 回答 1

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,因为 predicates 非常强大,而且在 store 中过滤你的结果更有效。

于 2012-12-08T03:00:32.620 回答