知道总计数,循环通过基本数组

时间:2015-09-17 02:10:40

标签: ios objective-c

我正在尝试转换像这样的数组

_Array = @[[[feeds objectAtIndex:0] objectForKey: @"title"],
           [[feeds objectAtIndex:1] objectForKey: @"title"],
           [[feeds objectAtIndex:2] objectForKey: @"title"],
           [[feeds objectAtIndex:3] objectForKey: @"title"],
           [[feeds objectAtIndex:4] objectForKey: @"title"],
           [[feeds objectAtIndex:5] objectForKey: @"title"],
           [[feeds objectAtIndex:6] objectForKey: @"title"],
           [[feeds objectAtIndex:7] objectForKey: @"title"],
           [[feeds objectAtIndex:8] objectForKey: @"title"],
           [[feeds objectAtIndex:9] objectForKey: @"title"],
           [[feeds objectAtIndex:10] objectForKey: @"title"],

           [[feeds objectAtIndex:xx] objectForKey: @"title"]];

进入循环。我知道阵列的总数。并且一直在尝试这样的事情......

for (int i = 0; i < dCount; i++) {
    [[feeds objectAtIndex:i] objectForKey: @"title"];

      }

但不确定如何将循环添加到数组中。

由于

1 个答案:

答案 0 :(得分:3)

我认为您要问的是如何使用循环向_Array数组添加元素,是否正确?

试试这个(假设_ArrayNSArrayfeeds包含词典):

NSMutableArray *tmpArray = [NSMutableArray array];
for (NSDictionary *dict in feeds) {
    [tmpArray addObject:dict[@"title"]];
}

_Array = [tmpArray copy]; // make it immutable

使用KVC更简单的方法是:

_Array = [feeds valueForKey:@"title"];

BTW - 标准命名约定规定变量和方法名称应以小写开头。请考虑将_Array更改为_array

评论更新:

你需要使用类似的循环作为我答案的第一部分:

NSMutableArray *tmpArray = [NSMutableArray array];
for (NSDictionary *dict in feeds) {
    NSString *imagePath = [[empty stringByAppendingPathComponent:dict[@"image"]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [tmpArray addObject:imagePath];
}
_images = [tmpArray copy];