应用程序因空数组而崩溃

时间:2018-02-12 07:18:37

标签: ios objective-c json xcode nsarray

NSString *strMethod;
NSString *strType = @"restaurant";
NSDictionary *params = @{@"type": strType};
NSString *strMethod = [NSString stringWithFormat:@"%@%@", API_CATEGORY_SHOP, @"en"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 manager.responseSerializer = [AFJSONResponseSerializer serializer];
 NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:[NSSet setWithObject:@"text/json"]];
 [contentTypes addObject:@"text/html"];
 [contentTypes addObject:@"application/json"];

 manager.responseSerializer.acceptableContentTypes = contentTypes;
 [manager POST:strMethod parameters:params progress:nil success:^(NSURLSessionDataTask *task, id response){

    if ([[response objectForKey:@"result"] intValue] == 1) {

        [_arrRestaurtentTypeList removeAllObjects];
        [_arrRestaurtentTypeList addObjectsFromArray:[response objectForKey:@"Main Category"]];

        NSDictionary *dictAll = [_arrRestaurtentTypeList lastObject];

        if (dictAll) {
            [_arrRestaurtentTypeList removeLastObject];
            [_arrRestaurtentTypeList insertObject:dictAll atIndex:0];
        }

        [_collRestaurentTypeList reloadData];
        [_tblRestaurent reloadData];

    }

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    ;
}];
}

由于未捕获的异常'NSRangeException'而终止应用程序,原因:' * - [__ NSArrayM objectAtIndex:]:索引0超出空数组的边界' * 第一次抛出调用堆栈: (0x182caa364 0x181ef0528 0x182c42e9c 0x182b72820 0x100858628 0x100857624 0x18c279670 0x18c279bdc 0x18c31ee74 0x18c3e58b0 0x18c371910 0x18c4b5c98 0x18c299240 0x18c298bb4 0x18c2988c0 0x18c298960 0x186cfce14 0x1010a528c 0x1010a9ea0 0x182c52544 0x182c50120 0x182b6fe58 0x184a1cf84 0x18c2c467c 0x10085e320 0x18268c56c) libc ++ abi.dylib:以NSException类型的未捕获异常终止

1 个答案:

答案 0 :(得分:1)

if ([[response objectForKey:@"result"] intValue] == 1) {

    [_arrRestaurtentTypeList removeAllObjects];
    [_arrRestaurtentTypeList addObjectsFromArray:[response objectForKey:@"Main Category"]];

    NSDictionary *dictAll = [_arrRestaurtentTypeList lastObject];

    if (dictAll) {
        [_arrRestaurtentTypeList removeLastObject];
        [_arrRestaurtentTypeList insertObject:dictAll atIndex:0];
    }

    [_collRestaurentTypeList reloadData];
    [_tblRestaurent reloadData];

}

使用以下代码更改此行

 if ([[response valueForKey:@"result"] count] >0){
for (NSDictionary *dict in [response valueForKey:@"result"]) {
                        NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
                        [newDict addEntriesFromDictionary:dict];
                        [_arrRestaurtentTypeList addObject:newDict];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [_tblRestaurent reloadData];

                    });