lakshmen
lakshmen

Reputation: 29094

Sorting an array by alphabetical order before it is selected by UIPickerView

I am new to iphone development and need some guidance to do custom sorting of an array in iOS. I would like to sort the objects that appear in the UIPickerView. The objects that are passed to the UIPickerView are in an array.

When I print the array out, it looks like this:

    "<ObjectsInfo: 0x1c5249f0>",
    "<ObjectsInfo: 0x1c524940>",
    "<ObjectsInfo: 0x1c5248e0>",
    "<ObjectsInfo: 0x1c524890>",
    "<ObjectsInfo: 0x1c524840>",
    "<ObjectsInfo: 0x1c524a90>",

When i print out the first object's name:

    ObjectsInfo *object = [objectModelName objectAtIndex:1];
    NSLog(@"%@",object.str_name);

It prints out: Alpha

The values given are examples. I would like to sort the array objectModelName in alphabetical order.

How do i do that?

I tried this:

[objectModelName sortUsingSelector:@selector(compare:)];

How do i do custom sorting based on the str_name so that it is in alphabetical order? Need some guidance... Really appreciate any help...

Upvotes: 1

Views: 1325

Answers (2)

Cullen SUN
Cullen SUN

Reputation: 3547

[objectModelName sortUsingSelector:@selector(compareItem:)];

In ObjectsInfo.h

  - (NSComparisonResult)compareItem:(ObjectsInfo *)anotherItem;

In ObjectsInfo.m

  - (NSComparisonResult)compareItem:(ObjectsInfo *)anotherItem{

    return [self.str_name compare:anotherItem.str_name options:NSCaseInsensitiveSearch];

  }

Upvotes: 3

iDev
iDev

Reputation: 23278

Try this.

NSArray *sortedArray = [objectModelName sortedArrayUsingComparator:^(ObjectsInfo *firstObject, ObjectsInfo *secondObject) {
            return [firstObject.str_name compare:secondObject.str_name];
        }];

Upvotes: 2

Related Questions