0

I am trying to create a NSSet of strings collected from an unknown (possibly large) number of objects' attributes.

The user of my app logs objects during the month - they have different attributes wheras i am only interested in the NSString *category name.

Object.h
NSString *category
...

During a month he may log between 10 and 1000 such objects, stored in coredata. The user can define own categories - and i have to find out which categories were used during that month (to create an export file).

Currently i do the following (pseudocode)

NSArray *allObjects = [_dataHandler fetchAllObjectsForMonth:monthToExport];
NSMutableSet *allCategoryNamesSet = [[NSMutableSet alloc]init];
for(Object *obj in allObjects){
    [allCategoryNamesSet addObject:obj.category];
}

Wheras this works, it gets really slow with a lot of objects as the fetching takes time and the iterating as well of course.

I have tried something like that as well:

NSArray *categories = [allObjects valueForKeyPath:@"category"];
NSSet *allCategorieNamesSet = [NSSet initWithArray:categories];

maybe i did something wrong but it didnt quite work :/

What i am interested in is, if there is a solution that could significantly speed up this process? something i might have overlooked.

Any ideas?

4

2 回答 2

3

If you are interested only in the (distinct) value of the category attribute, set

[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:@[@"category"]];
[request setReturnsDistinctResults:YES];

for your fetch request. The fetch request then return an array of dictionaries (instead of managed objects) containing the category values.

The advantage is that this "filtering" is done on the SQLite level. One disadvantage (or "caveat") is that this implies setIncludesPendingChanges:NO, i.e. the fetch request is done only against the saved database and does not include unsaved pending modifications.

于 2013-03-30T09:34:43.520 回答
1

Checkout MagicalRecord, which is a convenience library for working with Core Data. This should help you do a lot of these tasks.

Good luck.

于 2013-03-30T09:28:45.013 回答