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

我的未来我决定 提交于 2020-01-05 15:36:46

问题


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


回答1:


Try this.

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



回答2:


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

  }


来源:https://stackoverflow.com/questions/13265667/sorting-an-array-by-alphabetical-order-before-it-is-selected-by-uipickerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!