【问题标题】:First three items of of NSArray into an NSString?NSArray 的前三项变成一个 NSString?
【发布时间】:2011-08-18 10:43:04
【问题描述】:

将数组的前三个对象(如果数组有多大,则为 1 或 2 个)转换为逗号分隔的字符串的最有效方法是什么。我感觉有一种方法可以用积木解决这个问题,但我无法解决

对象是Bands,存储在bandArray中,每个band的属性都包含一个bandName。

所以输出会是这样的

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored

【问题讨论】:

    标签: iphone objective-c ios nsstring nsarray


    【解决方案1】:

    您可以为此使用subarrayWithRange:

    NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))] 
                      valueForKey:@"brandName"] 
                     componentsJoinedByString:@", "];
    

    【讨论】:

    • 并且,使用[brandArray valueForKeyPath:@"bandName"] 方法将bandNames 作为数组获取
    • @EmptyStack 你说得对,我忘记了这部分问题。已编辑。
    【解决方案2】:
    NSUInteger count = [bandArray count];
    if (count > 3){
        count = 3;
    }
    NSString * resultString = [[bandArray subarrayWithRange:NSMakeRange(0,count)]  componentsJoinedByString:@", "];
    

    【讨论】:

      【解决方案3】:

      您可以尝试以下方法(虽然我没有使用 Mac,但它完全未经测试

      int bandCount = 1;
      NSString *bands;
      for (NSString *band in bandArray) {
          if (bandCount > 3) break;
          if (bandCount == 1) {
              bands = [NSString stringWithFormat:@"%@", band];
          } else {        
              bands = [NSString stringWithFormat:@"%@, %@", bands, band];
          }
          bandCount ++;
      }
      

      【讨论】:

      • 实际上,请参阅@Jilouc 的答案,因为它比我的更简洁(也许更有效?):)
      【解决方案4】:

      可能不是最快但最简单的,谁知道苹果苹果在创建子数组时可能会做一些聪明的事情。

      [[array subarrayWithRange:NSMakeRange(0,MIN(array.length,3)] componentsJoinedByString:@","];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多