简体   繁体   English

用大写字母对NSArray进行排序

[英]Sort NSArray with capital letters

I have an NSArray that looks like this: 我有一个看起来像这样的NSArray

contactNamesArray = [[NSMutableArray alloc] initWithObjects:@"John Galt", @"Michael Wales", @"James Joyce", @"Shakespeare", nil];

From it, I want to make an NSArray that would have all the same values , but that would look like this: 从它,我想制作一个具有所有相同值NSArray ,但是看起来像这样:

newContactNamesArray = [[NSMutableArray alloc] initWithObjects:@"john galt", @"michael wales", @"james joyce", @"shakespeare", nil];

I want to do this because I want to make a search in that second array and I want to replace every capital letter in it with a normal letter. 我想这样做,因为我想在第二个数组中进行搜索,我想用普通字母替换其中的每个大写字母。

How do you do something like this in Objective-C? 你如何在Objective-C中做这样的事情? Thanks in advance! 提前致谢!

You can go through an array, and convert every element to lower case by calling 您可以浏览一个数组,并通过调用将每个元素转换为小写

[element lowercaseString]

on it. 在上面。 However, this is grossly suboptimal for implementing case-insensitive search: a better approach would be keeping strings as-is, and employ caseInsensitiveCompare method for your search instead. 但是,这对于实现不区分大小写的搜索来说非常不理想:更好的方法是保持字符串caseInsensitiveCompare ,并采用caseInsensitiveCompare方法代替搜索。

Why are you making a copy? 你为什么要复制? You can sort an NSArray in a case insensitive way: 您可以以不区分大小写的方式对NSArray进行排序:

NSArray *sortedContactNamesArray = [contactNamesArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

Also, bear in mind that sortedArrayUsingSelector returns an array with references to the original items, not copies of them. 另外,请记住sortedArrayUsingSelector返回一个数组,其中包含对原始项的引用,而不是它们的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM