1

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

lakshmen
  • 28,346
  • 66
  • 178
  • 276

2 Answers2

3

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

  }
Cullen SUN
  • 3,517
  • 3
  • 32
  • 33
2

Try this.

NSArray *sortedArray = [objectModelName sortedArrayUsingComparator:^(ObjectsInfo *firstObject, ObjectsInfo *secondObject) {
            return [firstObject.str_name compare:secondObject.str_name];
        }];
iDev
  • 23,310
  • 7
  • 60
  • 85
  • when i do that it says: "Incompatible pointer types assigning to 'NSMutableArray *_strong' from 'NSArray *_strong'".... – lakshmen Nov 07 '12 at 09:08
  • After your code,i assign back sortedArray to objectModelName. it looks like this:NSArray *sortedArray = [objectModelName sortedArrayUsingComparator:^(ObjectsInfo *firstObject, ObjectsInfo *secondObject) { return [firstObject.str_name compare:secondObject.str_name]; }];objectModelName = sortedArray; – lakshmen Nov 07 '12 at 09:15
  • Try using objectModelName = [NSMutableArray arrayWithArray:sortedArray]; after this line. – iDev Nov 07 '12 at 09:16
  • 1
    that line converts an array to mutablearray version of it? – lakshmen Nov 07 '12 at 09:19
  • ya... thanks... out of curiosity? could i use mutablecopy? e.g arrModelName =[sortedArray mutableCopy];? works the same right? – lakshmen Nov 07 '12 at 09:25
  • Yes, you can use that. If you are not using ARC, you might have to release it yourself. – iDev Nov 07 '12 at 09:33
  • one more qn: you are using blocks in terms of functional paradigm? am i right to say that? – lakshmen Nov 07 '12 at 12:13
  • I am not sure you can call blocks that way. Yes, it is kind of. – iDev Nov 07 '12 at 18:43