`
cenphoenix
  • 浏览: 158686 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

How to Sort An Array in Objective-C

阅读更多
Arrays are structures used to hold a list of objects. Sometimes though you may want to sort the order that the elements appear.

Doing this is actually pretty simple once you know how, essentially you will be using the NSArray sortedArrayUsingSelector method.

For example, if you create an array like so

NSMutableArray *anArray = [[NSMutableArray alloc] init];
[anArray addObject:@"B"];
[anArray addObject:@"A"];
[anArray addObject:@"C"];

and then write out the contents of the array to the log using a foreach loop the results will look like this:

[Session started at 2009-03-25 16:57:55 -0400.]
2009-03-25 16:57:58.647 TipOfTheWeek[3403:20b] B
2009-03-25 16:57:58.648 TipOfTheWeek[3403:20b] A
2009-03-25 16:57:58.649 TipOfTheWeek[3403:20b] C

Obviously, the contents of the array stay in the same order in which they were inserted.

What you could do is create another array, sorted, using the sortedArrayUsingSelector method of NSArray. Here is how:

NSArray *sortedArray = [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

The odd (for some anyway) piece of this code is the @selector(caseInsensitiveCompare:) component of the code. This is a method passed to the function that instructions NSArray on how to sort the array.

At any rate, if you run through the array as before and print out the results to the log you will get this:

[Session started at 2009-03-25 17:07:18 -0400.]
2009-03-25 17:07:21.832 TipOfTheWeek[3537:20b] A
2009-03-25 17:07:21.833 TipOfTheWeek[3537:20b] B
2009-03-25 17:07:21.834 TipOfTheWeek[3537:20b] C

As you can see, the this array is sorted. There you have it!

Comments, questions – a better way to do this? Let me know in the comments below!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics