gpt4 book ai didi

iphone - 在 Objective-C 中对数组进行排序

转载 作者:可可西里 更新时间:2023-11-01 06:26:10 24 4
gpt4 key购买 nike

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

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

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

我的问题是这里实际发生了什么。我真的不明白我做了什么。

第 1 行:我明白我已经创建了一个具有描述符的新对象。这有两个参数,一个是我要排序的列,一个是升序。

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

第 3 行:我知道这是在调用 sortUsingDescriptors 方法,但我还是很困惑,为什么这个函数需要一个数组。

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

非常感谢任何帮助

最佳答案

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.

实际上,您已经创建了一个描述符的对象。它描述了如何对数组进行排序。

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?

对了——您已经创建了一个包含单个对象的数组。您可以创建一个包含十个或十五个或八十七个排序描述符的数组,如果您真的想对那么多字段进行排序。更多时候,你使用一个、两个,也许三个。因此,如果您要对人员列表进行排序,您可以添加指定姓氏和名字的排序描述符。这样,具有相同姓氏的人将根据他们的名字在该组中排列。

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

同样,这样您就可以拥有主要、次要、第三(等)排序键。当您只想对一个键进行排序时,您可以有一个单独的方法,该方法采用单个排序描述符而不是数组。 NSArray 没有提供,但如果需要,您可以随时将其添加到类别中:

@category NSArray (SingleSortDescriptor)

- (NSArray*)sortUsingDescriptor:(NSSortDescriptor*)descriptor;

@end

@implementation NSArray (SingleSortDescriptor)

- (NSArray*)sortUsingDescriptor:(NSSortDescriptor*)descriptor
{
return [self sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
}

@end

关于iphone - 在 Objective-C 中对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com