2016-08-09 59 views
-1

我試圖在IOS創造價值靜態JSONArray使用Objective - C
創建的NSDictionary我想這樣如何與關鍵多個陣列和值

tabledata={ 
["name":"image 1","path":"img1.jpg"], 
["name":"image 2","path":"img2.jpg"], 
["name":"image 3","path":"img3.jpg"], 
["name":"image 4","path":"img4.jpg"], 
["name":"image 5","path":"img5.jpg"], 
["name":"image 6","path":"img6.jpg"], 
["name":"image 7","path":"img7.jpg"]} 

這是我的數據..請幫我任何一個我怎麼能在Objective-C申報..

回答

1

您可以創建字典像下面

NSDictionary *dict = @{ 
     @"array": @[ 
      @{ 
       @"name":@"image 1", 
       @"path":@"img1.jpg" 
      }, 
      @{ 
       @"name":@"image 2", 
       @"path":@"img2.jpg" 
      } 
      .... 
     ] 
    }; 

陣列陣列

NSArray *array = @[ 
      @{ 
       @"name":@"image 1", 
       @"path":@"img1.jpg" 
      }, 
      @{ 
       @"name":@"image 2", 
       @"path":@"img2.jpg" 
      } 
      .... 
     ]; 

對於GET值從NSDictionary

NSArray *array = NSDictionary[@"array"] 
NSDictionary *firstObj = array[0]; 
NSString *name = firstObj[@"name"] 
NSString *path = firstObj[@"path"] 

只是

NSDictionary *firstObj = array[0]; 
NSString *name = firstObj[@"name"] 
NSString *path = firstObj[@"path"] 
+0

謝謝您的答覆...... –

+0

歡迎您,如果我的解決方案是合適的,請註明您的問題作爲回答。謝謝 – iSashok

+0

如何從NSDictionary數組中獲取值? –

0

您可以JsonString到NSDicitonary。

NSError *jsonError; 
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding]; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData 
           options:NSJSONReadingMutableContainers 
            error:&jsonError]; 

它是使數組NSDictionary。

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array 
{ 
    id objectInstance; 
    NSUInteger indexKey = 0U; 

    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init]; 
    for (objectInstance in array) 
     [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]]; 

     return (NSDictionary *)[mutableDictionary autorelease]; 
} 
1

一個替代老的方法是:

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

NSMutableDictionary * dict1 = [[NSMutableDictionary alloc] init]; 
[dict1 setValue:@"image 1" forKey:@"name"]; 
[dict1 setValue:@"img1.jpg" forKey:@"path"]; 

NSMutableDictionary * dict2 = [[NSMutableDictionary alloc] init]; 
[dict2 setValue:@"image 2" forKey:@"name"]; 
[dict2 setValue:@"img2.jpg" forKey:@"path"]; 

NSMutableDictionary * dict3 = [[NSMutableDictionary alloc] init]; 
[dict3 setValue:@"image 3" forKey:@"name"]; 
[dict3 setValue:@"img3.jpg" forKey:@"path"]; 

[tableData addObject:dict1]; 
[tableData addObject:dict2]; 
[tableData addObject:dict3]; 

NSLog(@"%@",tableData); 

//To Fetch Values 
NSDictionary *dictionary1 = [tableData objectAtIndex:0]; 
NSLog(@"%@", [dictionary1 valueForKey:@"name"]); 
+0

謝謝你的迴應... –