gpt4 book ai didi

ios - NSArray 排序数组使用描述符 : New Copy or Retain?

转载 作者:行者123 更新时间:2023-11-29 10:51:17 24 4
gpt4 key购买 nike

根据 NSArray 类引用,有 4 种方法对数组进行排序:

1- sortedArrayUsingComparator:

2- sortedArrayUsingSelector:

3- sortedArrayUsingFunction:context:

4- sortedArrayUsingDescriptors:

它提到的前三种方法: 新数组包含对接收数组元素的引用,而不是它们的副本。但是对于它提到的第四种方法(描述符): 按照 sortDescriptors 的指定排序的接收数组的副本。

但下面的示例显示与其他 3 个方法一样,描述符也保留原始数组并且不返回它的新副本:

NSString *last = @"lastName";
NSString *first = @"firstName";

NSMutableArray *array = [NSMutableArray array];
NSDictionary *dict;

NSMutableString *FN1= [NSMutableString stringWithFormat:@"Joe"];
NSMutableString *LN1= [NSMutableString stringWithFormat:@"Smith"];

NSMutableString *FN2= [NSMutableString stringWithFormat:@"Robert"];
NSMutableString *LN2= [NSMutableString stringWithFormat:@"Jones"];

dict = [NSDictionary dictionaryWithObjectsAndKeys: FN1, first, LN1, last, nil];
[array addObject:dict];

dict = [NSDictionary dictionaryWithObjectsAndKeys: FN2, first, LN2, last, nil];
[array addObject:dict];

// array[0].first = "Joe" , array[0].last = "Smith"
// array[1].first = "Robert" , array[1].last = "Jones"

NSSortDescriptor *lastDescriptor =[[NSSortDescriptor alloc] initWithKey:last
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];

NSSortDescriptor *firstDescriptor =[[NSSortDescriptor alloc] initWithKey:first
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];

NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil];

NSArray *sortedArray = [array sortedArrayUsingDescriptors:descriptors];

// array[1] == sortedArray[0] == ("Robert" , "Jones")
// comparing array entries whether they are same or not:

NSLog(@" %p , %p " , [array objectAtIndex:1] , [sortedArray objectAtIndex:0] );
// 0x10010c520 , 0x10010c520

它显示两个数组中的对象相同,

最佳答案

“按 sortDescriptors 指定排序的接收数组的副本”意味着复制的是数组对象而不是数组中的元素。文档使用“复制”一词的原因是为了明确返回的数组与接收方不是同一个数组实例。

除了 initWithArray:copyItems:YES 会将原始数组中的第一级 项复制到新数组中,Cocoa 中永远不会复制数组中的元素.即使这样,此复制也是通过对元素调用 copyWithZone: 来完成的,因此需要注意的事项取决于数组中的元素。

请注意,Cocoa 是引用计数的,因此“深拷贝”的概念并不是天生内置的。这也是(部分) cocoa 中的数组对象有两种风格(NSArrayNSMutableArray)并且通常是不可变的(NSArray)的原因) 而不是像其他语言那样通常没有不可变和可变数组的概念。

参见 this SO answer了解如何获取 NSArray 的“深拷贝”。

关于ios - NSArray 排序数组使用描述符 : New Copy or Retain?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20354776/

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