Core data setReturnsDistinctResult not working

Posted by Moze on Stack Overflow See other posts from Stack Overflow or by Moze
Published on 2010-05-14T12:58:29Z Indexed on 2010/05/14 13:04 UTC
Read the original article Hit count: 330

Filed under:
|
|
|

So i'm building a small application, it uses core data database of ~25mb size with 4 entities. It's for bus timetables.

In one table named "Stop" there are have ~1300 entries of bus stops with atributes "name", "id", "longitude", "latitude" and couple relationships. Now there are many stops with same name but different coordinates and id. Search is implemented using NSPredicate. So I want to show all distinct stop names in table view, i'm using setReturnsDistinctResults with NSDictionaryResultType and setPropertiesToFetch. But setReturnsDistinctResult is not working and I'm still getting all entries.

Heres code:

- (NSFetchRequest *)fetchRequest {
    if (fetchRequest == nil) {
        fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Stop" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];
        NSArray *sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]];
        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setResultType:NSDictionaryResultType];
        [fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]]];
        [fetchRequest setReturnsDistinctResults:YES];
        DebugLog(@"fetchRequest initialized");
    }
    return fetchRequest;
}

/////////////////////

- (NSFetchedResultsController *)fetchedResultsController {
    if (self.predicateString != nil) {
        self.predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", self.predicateString];
        [self.fetchRequest setPredicate:predicate];
    } else {
        self.predicate = nil;
        [self.fetchRequest setPredicate:predicate];
    }
    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:self.fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionNameKeyPath cacheName:nil];

    return fetchedResultsController;
}  

//////////////

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [[fetchedResultsController objectAtIndexPath:indexPath] valueForKey:@"name"];

    return cell;
}

© Stack Overflow or respective owner

Related posts about xcode

Related posts about iphone