dispatch_async - [__ NSArrayM objectAtIndex:]:索引0超出空数组的边界

时间:2014-03-07 22:22:20

标签: ios objective-c nsmutablearray dispatch-async

我无法解决此错误:*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' ***

关于我如何做到这一点的任何想法?

似乎错误是由数组初始化引起的。

第一次执行该方法时,没有显示任何问题。该错误仅在第二次发生。

Dispatch_Async方法

-(IBAction)clickRandom:(id)sender{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self RequestJson];

        dispatch_async(dispatch_get_main_queue(), ^{
            [tableView reloadData];
        });
    });
}

RequestJson方法

-(void)RequestJson
{
    Name = [[NSMutableArray alloc] init];
    slug = [[NSMutableArray alloc] init];
    image = [[NSMutableArray alloc] init];
    view = [[NSMutableArray alloc] init];
    category = [[NSMutableArray alloc] init];

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

        NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
        array = [jsonArray objectForKey:@"videos"];

        for (int i = 0; i < [array count]; i++)
        {
            [Name addObject:[[array objectAtIndex:i] objectForKey:@"name"]];
            [slug addObject:[[array objectAtIndex:i] objectForKey:@"slug_video"]];
            [image addObject:[[array objectAtIndex:i] objectForKey:@"thumbnail_video_original"]];
            [view addObject:[[array objectAtIndex:i] objectForKey:@"views_video"]];
            [category addObject:[[array objectAtIndex:i] objectForKey:@"category_name_video"]];

        }
       [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}

因为崩溃日志是这样的:

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x2d77de7e __exceptionPreprocess + 126
1   libobjc.A.dylib                 0x37ada6c2 objc_exception_throw + 34
2   CoreFoundation                  0x2d6b3d90 -[__NSArrayM objectAtIndex:] + 228
3   Vigg                            0x00117a40 -[DEMOHomeViewController tableView:cellForRowAtIndexPath:] (DEMOHomeViewController.m:315)
4   UIKit                           0x30034310 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 404
5   UIKit                           0x2ffdc6c8 -[UITableView _updateVisibleCellsNow:] + 1796
6   UIKit                           0x2ffdbeec -[UITableView layoutSubviews] + 180
7   UIKit                           0x2ff0234e -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 342
8   QuartzCore                      0x2fb8893e -[CALayer layoutSublayers] + 138
9   QuartzCore                      0x2fb84162 CA::Layer::layout_if_needed(CA::Transaction*) + 346
10  QuartzCore                      0x2fb83ff4 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 12
11  QuartzCore                      0x2fb83a08 CA::Context::commit_transaction(CA::Transaction*) + 224
12  QuartzCore                      0x2fb8381a CA::Transaction::commit() + 310
13  QuartzCore                      0x2fb7d548 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 52
14  CoreFoundation                  0x2d748f64 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
15  CoreFoundation                  0x2d7468f2 __CFRunLoopDoObservers + 282
16  CoreFoundation                  0x2d746c3e __CFRunLoopRun + 734
17  CoreFoundation                  0x2d6b146c CFRunLoopRunSpecific + 520
18  CoreFoundation                  0x2d6b124e CFRunLoopRunInMode + 102
19  GraphicsServices                0x323eb2e6 GSEventRunModal + 134
20  UIKit                           0x2ff66840 UIApplicationMain + 1132
21  Vigg                            0x000f84c0 main (main.m:16)
22  libdyld.dylib                   0x37fd3ab2 tlv_initializer + 2

4 个答案:

答案 0 :(得分:1)

崩溃在您的表视图的数据源方法中,不在RequestJSON方法中(应该称为requestJSON;方法始终以小写字母开头)。

因此,您有一个空数组,您不期望它,并且您已将表视图中的行(或部分)的数量与实际包含数据的数据模型对象分离。

您需要发布实际崩溃的方法的来源。

答案 1 :(得分:1)

您正在后台线程上调用UIKit方法,这会导致随机崩溃。替换此行

[tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade]; 

使用这些行(从clickRandom移动到requestJson)

dispatch_async(dispatch_get_main_queue(), ^{
   [tableView reloadData];
});

要么是这样,要么将reloadSections来电包裹在dispatch_async(dispatch_get_main_queue()

答案 2 :(得分:0)

我做了一些重构,提出了一些处理错误和查看响应的建议

- (void)someMethodCalledInViewDidLoad_viewWillAppear_orLoadView_beforeRequestJson
{
    name = [NSMutableArray array];
    slug = [NSMutableArray array];
    image = [NSMutableArray array];
    view = [NSMutableArray array];
    category = [NSMutableArray array];
}

-(void)requestJson
{
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
    array = [jsonArray objectForKey:@"videos"];
    // you can log your jsonArray or array to see what values are present or not
    if (array.count > 0) {
        for (int i = 0; i < [array count]; i++)
        {
            [name addObject:[[array objectAtIndex:i] valueForKey:@"name"]];
            [slug addObject:[[array objectAtIndex:i] valueForKey:@"slug_video"]];
            [image addObject:[[array objectAtIndex:i] valueForKey:@"thumbnail_video_original"]];
            [view addObject:[[array objectAtIndex:i] valueForKey:@"views_video"]];
            [category addObject:[[array objectAtIndex:i] valueForKey:@"category_name_video"]];

        }
       [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
   }
}

-(IBAction)clickRandom:(id)sender{
    [self requestJson];
}

答案 3 :(得分:0)

你有一个空数组。你试图调用[array objectAtIndex:0]。 0超出空数组的范围(任何超出空数组的范围)。