2013-11-21 64 views
-4

我有下面的JSON文件,我把它做objective c - 如何從NSArray動態獲取元素?

NSArray *allFrames = [self.campaign.form.gameParams objectForKey:@"frames"]; 

我想達到什麼保存在一個數組,是把從URL水平方向的所有影像在視圖中。我的問題是我想動態地做到這一點,因爲元素的數量可能會改變。

frames =  (
      { 
     horizontal = "http://mysite.co.uk/files/frames/5_h.png"; 
     vertical = "http://mysite.co.uk/files/frames/5_v.png"; 
    }, 

      { 
     horizontal = "http://mysite.co.uk/files/frames/6_h.png"; 
     vertical = "http://mysite.co.uk/files/frames/6_v.png"; 
    } 
      { 
     horizontal = "http://mysite.co.uk/files/frames/6_h.png"; 
     vertical = "http://mysite.co.uk/files/frames/6_v.png"; 
    } 
); 

我直到現在做的是靜態存儲的URL這樣

NSDictionary *frames = allFrames[0]; 

    NSString * link1 = [frames objectForKey:@"horizontal"]; 


    NSDictionary *frames = allFrames[1]; 

    NSString * link2 = [frames objectForKey:@"horizontal"]; 


    NSDictionary *frames = allFrames[2]; 

    NSString * link3 = [frames objectForKey:@"horizontal"]; 

然後將URL轉換成圖像

UIImage *webImage1 = [UIImage imageWithData: 
            [NSData dataWithContentsOfURL: 
            [NSURL URLWithString:link1]]]; 
                   etc 

任何想法怎麼辦呢?

+3

迭代這個數組... – Wain

+0

你能解釋一下嗎?我在這個新的 – chris

+2

我簡直不敢相信谷歌沒有拿出一些有用的東西。這個問題重複了很多... – 2013-11-21 15:17:41

回答

1

這樣的事情?

NSMutableArray *imageArray = [[NSMutableArray alloc] init]; 

for (int i = 0; i < allFrames.count; i++) { 
    NSDictionary *dict = allFrames[i]; 
    NSString *link = dict[@"horizontal"]; 

    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:link]]]; 

    [imageArray addObject:image]; 
} 
0

水平數據可以使用NSArray的valueForKey過濾。

NSArray *horizontalImages = [frames valueForKey:@"horizontal"]; 

for(NSString *urlString in horizontalImages) 
{ 
UIImage *webImage1 = [UIImage imageWithData: 
            [NSData dataWithContentsOfURL: 
            [NSURL URLWithString: urlString]]]; 
} 
0
NSArray *dict = @[@{@"horizontal": @"http://mysite.co.uk/files/frames/5_h.png"}, @{@"horizontal": @"http://mysite.co.uk/files/frames/6_h.png"}, @{@"horizontal": @"http://mysite.co.uk/files/frames/6_h.png"}]; 
NSMutableArray *horizontalLinks = [NSMutableArray array]; 
[dict enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    [horizontalLinks addObject:[obj objectForKey:@"horizontal"]]; 
}]; 

NSLog(@"Horizontal Links: %@", horizontalLinks); 

會給你:

Horizontal Links: (
    "http://mysite.co.uk/files/frames/5_h.png", 
    "http://mysite.co.uk/files/frames/6_h.png", 
    "http://mysite.co.uk/files/frames/6_h.png" 
)