0

I create an array with string names as shown below

NSMutableArray *strings = [[NSMutableArray alloc]init];
[string addObject:@"string1"];
[string addObject:@"string2"];
[string addObject:@"string3"];
[string addObject:@"string4"];

and I create a button. Whenever I click the button the strings are exchanged how can I do this?

Jasarien
  • 58,279
  • 31
  • 157
  • 188
Mahesh Babu
  • 3,395
  • 9
  • 48
  • 97
  • possible duplicate of [How can one sort an NSMutableArray of NSMutableArrays containing NSStrings?](http://stackoverflow.com/questions/1103317/how-can-one-sort-an-nsmutablearray-of-nsmutablearrays-containing-nsstrings) – Brad Larson Sep 16 '10 at 14:55
  • See also [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – Brad Larson Sep 16 '10 at 14:55

2 Answers2

5

EDIT:

Looks like you do not really lack basic knowledge. You can call this method in NSArray after you add your objects:

This method is the simplest way to do your job:

NSArray *sortedStrings = [strings sortedArrayUsingSelector:@selector(compare:)];

More about sortedArrayUsingSelector:

vodkhang
  • 18,639
  • 11
  • 76
  • 110
0

You can see NSArray class reference about following methods.

Sorting

  • sortedArrayHint
  • sortedArrayUsingFunction:context:
  • sortedArrayUsingFunction:context:hint:
  • sortedArrayUsingDescriptors:
  • sortedArrayUsingSelector:
  • sortedArrayUsingComparator:
  • sortedArrayWithOptions:usingComparator:

As for your problem, you can sort strings by
[strings sortedArrayUsingSelector:@selector(compare:)].

AechoLiu
  • 17,522
  • 9
  • 100
  • 118
  • [strings sortedArrayUsingSelector:@selector(compare:)] i am try using this but strings are not exchanged. – Mahesh Babu Sep 16 '10 at 13:46
  • Does your string look really like the above? Is it localized to some specific languages (e.g Chinese, Japanese)? – vodkhang Sep 16 '10 at 14:04
  • 1
    the method works fine, but you are adding the strings to the NSArray in an already sorted order. try putting "string4" at first position then run. – vaitrafra Sep 16 '10 at 14:25
  • try `strings = [strings sortedArrayUsingSelector:@selector(compare:)];` as it doesn't work in-place. – vikingosegundo Sep 17 '10 at 05:26