添加objectAtIndex:1 -9,当存在于NSDictionary时

时间:2012-12-29 12:37:53

标签: objective-c ios nsdictionary

我想从NSDictionary

中获取一些对象

一次10个,所以objectAtIndex 0到9

现在只添加:

AddObject:[[[json objectForKey:@"one"] objectAtIndex:1] ObjectForKey:@"likes"];

和那9次,是否有更简单的方法来做到这一点,并且只在对象存在时添加。

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个:

NSArray *shotsArr = [json objectForKey:@"shots"];
NSMutableArray *allViewsCounts = [NSMutableArray array];
for (NSDictionary *shotDict in shotsArr) {
    NSNumber *viewsCount = [shotDict objectForKey:@"views_count"];
    [allViewsCounts addObject:viewsCount];
}

如果您希望此数组中只有10个对象:

__block NSMutableArray *allViewsCounts = [NSMutableArray array];
[shotsArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *shotDict = obj;
    NSNumber *viewsCount = [shotDict objectForKey:@"views_count"];
    [allViewsCounts addObject:viewsCount];
    if (idx == 10) {
        *stop = YES;
    }
}];

答案 1 :(得分:0)

简单地用于循环

for (int i=0;i<10;i++){
     if([[[json objectForKey:@"one"] objectAtIndex:i] ObjectForKey:@"likes"]){
          AddObject:[[[json objectForKey:@"one"] objectAtIndex:i] ObjectForKey:@"likes"];
     }
}