Monday, February 1, 2010

Creating an array from a set

I'm working with Core Data, and ran into the problem that I need ordered data from a result set from Core Data. the difficulty is that it's not a primary query, but from a relationship. My solution was to create a category for NSSet that allows me to create an ordered array (based on a sort criteria):

// An extension of NSSet to get a sorted array from that set.

@interface NSSet(ArrayMethods)

- (NSArray*) getSortedArray:(NSString*) primaryKey;


@implementation NSSet(ArrayMethods)

- (NSArray*) getSortedArray:(NSString*) primaryKey


NSSortDescriptor *sortDesc =

[[NSSortDescriptor alloc] initWithKey:primaryKey


selector:@selector(localizedCaseInsensitiveCompare:) ];

NSArray *descArray=[[NSArray alloc] initWithObjects:sortDesc,nil] ;

NSArray *returnValue=[[self allObjects] sortedArrayUsingDescriptors:descArray] ;

[descArray release];

return returnValue ;



There are probably better ways to do this, and I might find a memory error in there at some point in time,(although I think I have it right).

No comments:

Post a Comment