问题
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