简体   繁体   中英

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...

[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];

  }

Try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM