尝试将nsdictionary分配给我的nsarray但应用程序每次都崩溃

时间:2016-08-18 09:29:30

标签: ios objective-c nsmutablearray nsarray nsdictionary

我正在尝试将我的NSDictionary分配给我的NSArray但应用程序每次崩溃都是我的代码:

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",
                    @"45.5016889",@"hotelLat",
                    @"-73.567256",@"hotelLong", nil];
    }

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

这是我传递数据的时候

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];

1 个答案:

答案 0 :(得分:1)

一个词典不起作用,因为当前状态的键不是唯一的。关于可能解决方案的两点建议,

1)我认为最好是使用您要存储的属性创建一个Hotel对象,并在for循环中初始化这些对象。如果你愿意,我可以给你一个例子。

2)如果您想使用字典,您可以执行下面我列出的操作,尽管您可以尝试其他许多变体。

    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",
                               @"startingfrom",
                               @"city",
                               @"distance",
                               @"imagesnames",
                               @"numberofstars",
                               @"hotelLat",
                               @"hotelLong"];

      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],
                          @"45.5016889",
                          @"-73.567256"];

      [arrayOfHotels addObject:[NSDictionary dictionaryWithObjects:columnNames forKeys:values]];
   }