在 Objective-C 中对数组进行排序 [英] Sorting arrays in Objective-C

查看:65
本文介绍了在 Objective-C 中对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试自学 Objective-C,并且正在做一个需要对数组进行排序的练习.

I'm currently trying to teach myself Objective-C and was playing around with an exercise where I needed to sort an array.

我设法使用以下代码完成它:

I managed to complete it using the following code:

NSSortDescriptor * newSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:TRUE];
NSArray *sortDescriptors = [NSArray arrayWithObject:newSortDescriptor];
[self.theBookStore sortUsingDescriptors:sortDescriptors];

我的问题是关于这里实际发生的事情.我真的不明白我做了什么.

My question is about what is actually happening here. I don't really understand exactly what I've done.

第 1 行:我在这里理解我创建了一个具有描述符的新对象.这有两个参数,我要排序的列和升序.

Line 1: I understand here I've created a new object that has a descriptor. This has two parameters, the column I want to sort on and that it is ascending.

第 2 行:这是我感到困惑的行.为什么我需要一个排序描述符数组?当我阅读这段代码时,我怀疑它创建了一个只有一行的数组,这样对吗?

Line 2: This is the line I'm confused about. Why do I need an array of sort descriptors? When I read this code I suspect it creates an array with only one row is that correct?

第 3 行:我知道这是调用 sortUsingDescriptors 方法,但同样,我的困惑是为什么这个函数需要一个数组.

Line 3: I understand that this is calling the sortUsingDescriptors method but again, my confusion is why this function expects an array.

我已经阅读了文档,但我真的在寻找一个简单的解释.

I've read the documentation but I'm really looking for a simple explanation.

非常感谢任何帮助

推荐答案

  • 第 1 行:.. 是的,你的权利.您正在创建一个名为 NSSortDescriptor 的自定义对象.该对象定义了一个要排序的属性.您确实输入了标题".因此,要排序的数组中的对象将在该属性之后排序(yourObject.title "kind-of").

    • Line 1: .. yes your right. You are creating a custom object called NSSortDescriptor. That object defines a attribute to sort after. You did enter "title". So the objects in your array-to-sort will be sorted after that property (yourObject.title "kind-of").

      第2行:因为排序方法(sortUsingDescriptors)总是需要一个数组,所以需要创建一个只有一个对象的NSArray.好吧……看起来有点傻.但绝对有道理.假设您想按照两个条件进行排序(比如标题",然后是城市").

      Line 2: Because the sorting method (sortUsingDescriptors) always needs a array, you need to create a NSArray with only one object. Okay, ... looks kind of stupid. But makes absolute sense. Lets say you would like to sort after two criteria (lets say "title", then "city").

      第 3 行:是的,这里必须是一个数组,因为按照多个条件进行排序.

      Line 3: Yes heres must be a array because of sorting after more then one criteria.

      并始终保持内存清洁:在第 1 行,您确实分配/初始化了一个 NSSortDescriptor.所以使用后清理(如果你没有使用ARC).所以添加一行:

      And always keep the memory clean: On line 1 you did allocate/init a NSSortDescriptor. So clean up after using it (if you are not using ARC). So add a line:

      [newSortDescriptor release];
      

      这篇关于在 Objective-C 中对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆