2

I have a class Events

@interface MeEvents : NSObject {
    NSString* name;**strong text**
    NSString* location;

}

@property(nonatomic,retain)NSString* name;strong text
@property(nonatomic,retain)NSString* location;

In my NSMutablArray I add object of Events

Events* meEvent;
[tempArray addObject:meEvent];

Please tell me how to sort this array by member name.

4 Answers 4

4
NSSortDescriptor *sortDes = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
        [tempArray_ sortUsingDescriptors:[NSArray arrayWithObject:sortDes]];
        [sortDes release];
Sign up to request clarification or add additional context in comments.

2 Comments

This give SIGABRT error.Sir my array return class object like <Events 0xab00240> Then i receive object in Events* meEvent=[temparray objectAtIndex:i]; NSLog(@"Name %@",meEvent.eventname);
@SawanCool: You have to define the key in ["initWithKey:""].In the above code i just give an example as "name".Please init the sortDescriptor with your key.
2

The easiest way is to use sortUsingComparator: like this:

[tempArray sortUsingComparator:^(id a, id b) {
    return [[a name] compare:[b name]];
}];

If you are sorting these strings because you want to show a sorted list to the user, you should localizedCompare: instead:

[tempArray sortUsingComparator:^(id a, id b) {
    return [[a name] localizedCompare:[b name]];
}];

Or you might want to use localizedCaseInsensitiveCompare:.

Comments

2

Declare this at the top of the implementation file above @interface line

NSComparisonResult sortByName(id firstItem, id secondItem, void *context);

Following is the implementation for the method

NSComparisonResult sortByName(id item1, id item2, void *context)
{
    NSString *strItem1Name = [item1 name];
    NSString *strItem2Name = [item2 name];

    return [strItem1Name compare:strItem2Name]; //Ascending for strItem1Name you can reverse comparison for having descending result
}

This is how you would call it

[tempArray sortUsingFunction:sortByName context:@"Names"];

Comments

1

You can sort the array using NSArray's

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

method

For more detail, see this SO answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.