Monday, August 02, 2010

iPhone: Sort NSMutableArray of Custom Objects by Property

Bookmark.h

//

// Bookmark.h

// Mapjack

//

// Created by Benjamin Rafael F. Intal on 8/2/10.

// Copyright 2010 __MyCompanyName__. All rights reserved.

//


#import



@interface Bookmark : NSObject {

NSString *name;

NSString *address;

NSString *position;

}


@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *address;

@property (nonatomic, copy) NSString *position;


@end



Bookmark.m

//

// Bookmark.m

// Mapjack

//

// Created by Benjamin Rafael F. Intal on 8/2/10.

// Copyright 2010 __MyCompanyName__. All rights reserved.

//


#import "Bookmark.h"



@implementation Bookmark


@synthesize name;

@synthesize address;

@synthesize position;


- (id) initWithCoder: (NSCoder *)coder

{

self = [[Bookmark alloc] init];

if (self != nil)

{

self.name = [coder decodeObjectForKey:@"name"];

self.address = [coder decodeObjectForKey:@"address"];

self.position = [coder decodeObjectForKey:@"position"];

}

return self;

}


- (void) encodeWithCoder: (NSCoder *)coder

{

[coder encodeObject:name forKey:@"name"];

[coder encodeObject:address forKey:@"address"];

[coder encodeObject:position forKey:@"position"];

}


@end



Somewhere in the controller, declare your NSMutableArray of Bookmark objects (or any other objects), then sort using:

In this sample, I sorted using the name property

// Sort the bookmarks by name

NSSortDescriptor *firstDescriptor =

[[[NSSortDescriptor alloc]

initWithKey:@"name"

ascending:YES

selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];

NSArray * descriptors =

[NSArray arrayWithObjects:firstDescriptor, nil];

NSArray * sortedArray =

[localBookmarks sortedArrayUsingDescriptors:descriptors];



0 Comments:

Post a Comment

<< Home