问题描述
我有一个 NSMutableArray,称为类别,其中包含一个名为 CategoryItem 的对象.CategoryItem 有一个 NSString 属性,*text.现在我将如何根据元素的 text 属性对这个 Array 进行排序?对不起,如果这没有意义,我是新手.
I have an NSMutableArray, called categories, which contains an object called CategoryItem. CategoryItem has an NSString property, *text. Now how would I sort this Array based on the text property of the elements? Sorry if this doesn't make sense, I'm new to all this.
我试过了:
[categories sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
但是失败了.
推荐答案
那是因为您试图根据每个对象对数组进行排序,而不是它包含的字符串.
That's because you're trying to sort the array based on each object, not on the string it contains.
您需要使用 NSSortDescriptor 的实例来对数组进行排序.您可以像这样创建一个:
You need to use an instance of NSSortDescriptor to sort your array. You can create one like this:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"text" ascending:YES];
那么:
[categories sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
这篇关于按字母顺序对 NSMutableArrays 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!