How to Sort An Array in Objective-C

本文介绍如何使用NSArray的sortedArrayUsingSelector方法对数组中的元素进行排序。通过实例演示了创建数组并利用caseInsensitiveCompare:方法实现字母顺序排列的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值