iOS Developer
iOS Developer

Reputation: 41

Adding Objects from NSMutableDictionary to NSMutableArray

I am new in ios development, I want to add some object from database which I managed to put into a NSMutabledictionary and I want to put into a NSMutableArray to display in a UITableView. Below is my .m file code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    jsonURL = [NSURL URLWithString:@"http://localhost:8888/read_product_list.php"];

    //jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];

    NSData *data = [NSData dataWithContentsOfURL:jsonURL];
    [self getData:data];    
}

-(void) getData:(NSData *) response {
    NSError *error;

    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
    //NSLog(@"%@", json);


    jsonArray = [[NSMutableArray alloc] init];
    /*for(int i = 0; i < json.count; i++){
        [jsonArray addObject:[json objectForKey:];
    }*/

    //NSLog(@"%@", jsonArray);

}

Thank you in advance!

Upvotes: 1

Views: 1520

Answers (2)

Ashish Chauhan
Ashish Chauhan

Reputation: 1376

To get all values into an array

NSMutableArray *jsonArray = [[NSMutableArray alloc] initWithArray:[json allValues]];

To get all keys into an array

NSMutableArray *jsonKeyArray = [[NSMutableArray alloc] initWithArray:[json allKeys]];

Upvotes: 0

mattjgalloway
mattjgalloway

Reputation: 34902

If you want the values of the dictionary then try:

jsonArray = json.allValues;

It won't be ordered by anything interesting though, so you might want to order it afterwards as well.

But, if this really is your JSON:

[{"0":"Samsung LCD 42 TV","Name":"Samsung LCD 42 TV","1":"7900.99","Price":"7900.99","2":"Buy the new Samsung 42 nth TV from Hi-if. available only this coming weekend. ","Description":"Buy the new Samsung 42 nth TV from Hi-if. available only this coming weekend. "},{"0":"iPhone 4s","Name":"iPhone 4s","1":"7000","Price":"7000","2":"Buy a brand new iPhone 4s from Orange with a lot of Features such as Siri, 3G and Wi-Fi.","Description":"Buy a brand new iPhone 4s from Orange with a lot of Features such as Siri, 3G and Wi-Fi."}]

Then that's actually an array anyway, so you probably just want:

jsonArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];

Upvotes: 3

Related Questions