Vix Hunk Vix Hunk - 1 year ago 89
iOS Question

Trying to assign nsdictionary to my nsarray but app crashes everytime

I am trying to assign my NSDictionary to my NSArray but app Crashes everytime here is my code:

NSDictionary *dict = [[NSDictionary alloc]init];
for (int i=0; i< myMutableArray.count; i++) {
dict = [NSDictionary dictionaryWithObjectsAndKeys:[[myMutableArray objectAtIndex:i]xmlhotel_name], @"hotelname",
[PriceArray objectAtIndex:i], @"startingfrom",
[[myMutableArray objectAtIndex:i]xmlhotel_city],@"city",
[DistanceArray objectAtIndex:i],@"distance",
[[myMutableArray objectAtIndex:i]xmlhotel_image],@"imagesnames",
[[myMutableArray objectAtIndex:i]xmlhotel_stars],@"numberofstars",
@"-73.567256",@"hotelLong", nil];

NSArray *myArray = @[@{[dict allKeys] : [dict allValues]}];

and here is when i am passing data

BookATableController = [self.storyboard instantiateViewControllerWithIdentifier:@"bookatable"];
BookATableController.myMutableArray=[[NSMutableArray alloc]initWithArray:self.rssOutputData];/// Passing Data
BookATableController.PriceArray=[[NSMutableArray alloc]initWithArray:rssHotelPrice];/// Passing Data
BookATableController.DistanceArray=[[NSMutableArray alloc]initWithArray:rssHotelDistance];/// Passing
[self.view addSubview:BookATableController.view];
[self addChildViewController:BookATableController];
[BookATableController didMoveToParentViewController:self];

Answer Source

One dictionary wouldn't work because your keys in the current state are not unique. Two suggestions for possible solutions,

1) I think the best is to create a Hotel object with the properties you want to store and initialize those objects in your for loop. I can give you an example if you would like one.

2) If you want to use the dictionary, you could do something like I've listed below, although there are probably many other variations you could try.

    NSMutableArray *arrayOfHotels = [[NSMutableArray alloc] init];
    // 5 is random, you can use the count from 'myMutableArray'
    for (int i=0; i < 5; i++) {

        NSArray *columnNames = @[@"hotelname",

      NSArray *values = @[[[myMutableArray objectAtIndex:i]xmlhotel_name],
                          [PriceArray objectAtIndex:i],
                          [[myMutableArray objectAtIndex:i]xmlhotel_city],
                          [DistanceArray objectAtIndex:i],
                          [[myMutableArray objectAtIndex:i]xmlhotel_image],
                          [[myMutableArray objectAtIndex:i]xmlhotel_stars],

      [arrayOfHotels addObject:[NSDictionary dictionaryWithObjects:columnNames forKeys:values]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download