【问题标题】:How do I return an array with the initial letters of all the objects in another array?如何返回一个数组,其中包含另一个数组中所有对象的首字母?
【发布时间】:2010-11-18 08:55:28
【问题描述】:

我正在将普通的 tableview 转换为分段的 tableview。我希望节标题是节中项目的第一个字母。

这是我目前在 titleForHeaderInSection 方法中的内容:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Name"
                                              ascending:YES] autorelease];
NSArray *sortedArray;
NSMutableArray *commonNameArray = [tableDataSource valueForKey:@"Name"];

NSArray *uniquearray;
uniquearray = [[NSSet setWithArray:commonNameArray] allObjects];
sortedArray = [uniquearray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

此代码删除重复的标题并按字母顺序对列表进行排序。现在我只需要将数组中的字符串转换为第一个字母。解决此问题的最佳方法是什么?

【问题讨论】:

    标签: iphone arrays uitableview sorting


    【解决方案1】:

    感谢您的帮助。在一个难得的灵感时刻,我刚刚开始工作。这就是我所做的。有人认为这样做有什么问题吗?

    -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
         NSSortDescriptor *sortDescriptor;
         sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"CommonName"
                    ascending:YES] autorelease];
         NSArray *sortedArray;
         NSMutableArray *commonNameArray = [tableDataSource valueForKey:@"CommonName"];
    
         NSArray *uniquearray;
         uniquearray = [[NSSet setWithArray:commonNameArray] allObjects];
         sortedArray = [uniquearray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    
         NSString *stringForFirstLetter = [[sortedArray objectAtIndex:section] substringToIndex:1];
    
    return stringForFirstLetter;}
    

    【讨论】:

      【解决方案2】:
      NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
      for( NSString *string in [tableDataSource valueForKey:@"Name"] )
          [firstCharacters addObject:[string substringToIndex:1]];
      
      NSArray *uniquearray = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
      

      【讨论】:

      • 谢谢!这比我在下面提出的解决方案要优雅一些。我刚刚添加: return [uniquearray objectAtIndex:section];它就像一个魅力。
      • 不仅优雅 - 而且效率更高......你不应该在 titleForHeaderInSection: 中这样做 - 你应该保留你的 uniqueArray 作为成员变量并在 dealloc 处释放。您正在创建一个包含所有名称的数组,一个排序的版本,然后挑选一个元素并获取第一个字符。我正在制作一组只有第一个字符,然后是一个排序版本 - 这两个版本的长度最多为 36 个字符(而不是 CommonName 的所有成员中的 # 个字符)
      • 感谢您的建议。我现在在 viewDidLoad 方法中放置了 unique 的声明,然后调用:return [arrayOfInitialLetters objectAtIndex:section];在 titleForHeaderInSection 方法中。
      • 在尝试调用 -substringToIndex: 之前,真的需要检查字符串的 -length。如果字符串为空,NSString 会抛出异常。
      猜你喜欢
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 2019-06-05
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多