如何从NSArray中删除括号?

时间:2014-01-16 18:28:30

标签: ios objective-c arrays nsarray

我的数组中包含每个索引的数组。

array is :(
        (
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-19g1.jpg",
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-20g2.jpg",
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-20g3.jpg"
    ),
        (
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-49y1.jpg",
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-50y2.jpg"
    ),
        (
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg",
        "http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg"

    )
)

我想制作一个类似

的数组
  (  
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg",
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg", 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg",
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg",                    
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg",
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg"
    )

如何在数组中消除(),()并创建一个包含url的单个数组。

4 个答案:

答案 0 :(得分:8)

你需要制作一个新阵列:

NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSArray *a in array)
    [newArray addObjectsFromArray:a];

答案 1 :(得分:6)

您可以使用键值编码运算符“@unionOfArrays”来展平数组:

NSArray *nested = @[@[@"A1", @"A2", @"A3"], @[@"B1", @"B2", @"B3"], @[@"C1", @"C2", @"C3"]];
NSArray *flattened = [nested valueForKeyPath:@"@unionOfArrays.self"];

NSLog(@"nested = %@", nested);
NSLog(@"flattened = %@", flattened);

输出:

nested = (
        (
        A1,
        A2,
        A3
    ),
        (
        B1,
        B2,
        B3
    ),
        (
        C1,
        C2,
        C3
    )
)
flattened = (
    A1,
    A2,
    A3,
    B1,
    B2,
    B3,
    C1,
    C2,
    C3
)

答案 2 :(得分:3)

您需要编写代码来遍历外部数组,将第二级数组的内容复制到“平面”数组。像这样:

(根据Carl Norum的帖子编辑,使用addObjectsFromArray)

-(NSArray )flattenArray: (NSArray *) sourceArray;
{
  NSMutableArray *result = [[NSMutableArray alloc] init];
  for (NSArray *array sourceArray)
  {
  //Make sure this object is an array of some kind. 
  //(use isKindOFClass to handle different types of array class cluster)
  if ([array isKindOfClass: [NSArray class])
  {
    [result addObjectsFromArray: array];
  }
  else
  {
    NSLog(@"Non-array object %@ found. Adding directly.", array);
    [result addObject: array];
  }
  return [result copy]; //return an immutable copy of the result array
}

答案 3 :(得分:2)

你必须规范你的数组 循环遍历数组,然后遍历所有子数组并将它们添加到另一个数组 这样的事情应该足以让你开始:here