Question

I have been to get an answer to my question of sorting data using NSSortDescriptor. I'm working on Core data app, lets say, i have a photographer and photos entities (one to many) one photographer can have many photos. What i need to do is to be able to show list of photographers sorted by their latest photos. so if Photographer A uploaded photo yesterday and Photographer B uploaded photo today, i need to show this in my TableView

Photographer B Photographer A

I'm using this code below that is sorting photographers by their timeStamp, i have same timeStamp attribute in Photos as well. how would i sort Photographers by their taken photo time stamp?

I can't use @"Photos.timeStamp" because, photos are NSSet, there may be multiple photos...

- (NSFetchedResultsController *)PhotographerFRC
{
    if (!_PhotographerFRC) {

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@“Photographer"];

        fetchRequest.sortDescriptors =@[[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:NO]];

        //[fetchRequest setFetchBatchSize:20];

         _PhotographerFRC = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:MOC sectionNameKeyPath:nil cacheName:nil];

        _PhotographerFRC.delegate = self;
    }
    return  _PhotographerFRC;
}
Was it helpful?

Solution

Create an additional attribute on Photographer called lastPhotoDate and set this whenever a new Photo gets created by overriding the addPhotosObject method on the Photographer subclass.

Below is an example

//
//  Company.h
//  CoreDataLibraryApp
//
//  Created by Duncan Groenewald on 13/01/2014.
//  Copyright (c) 2014 OSSH Pty Ltd. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Person, Program;

@interface Company : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *programs;
@property (nonatomic, retain) NSSet *employees;
@end

@interface Company (CoreDataGeneratedAccessors)

- (void)addProgramsObject:(Program *)value;
- (void)removeProgramsObject:(Program *)value;
- (void)addPrograms:(NSSet *)values;
- (void)removePrograms:(NSSet *)values;

- (void)addEmployeesObject:(Person *)value;
- (void)removeEmployeesObject:(Person *)value;
- (void)addEmployees:(NSSet *)values;
- (void)removeEmployees:(NSSet *)values;

@end



- (void)addEmployeesObject:(Person *)value {

    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];

    [self willChangeValueForKey:@"employees"
          withSetMutation:NSKeyValueUnionSetMutation
          usingObjects:changedObjects];
    [[self primitiveEmployees] addObject:value];
    [self didChangeValueForKey:@"employees"
          withSetMutation:NSKeyValueUnionSetMutation
          usingObjects:changedObjects];

   self.lastPhotoDate = value.timeStamp;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top