iOS核心数据NSRangeException

时间:2014-06-12 18:55:05

标签: ios json core-data nsrangeexception

我有一个问题我无法解决。我用Core Data框架创建了一个iOS应用程序。一切都很顺利,直到我得到NSRangeException。我在函数中遇到这个异常,它检查应用程序数据是否需要更新。

我的代码是:

- (BOOL) isTimetableUpdatedWithJSONData:(NSMutableDictionary*) data
{
    appDelegate = [[UIApplication sharedApplication] delegate];
    managedObjectContext = [appDelegate managedObjectContext];

    //Do database update check logic here
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MobileTimetableDataHash"     inManagedObjectContext:managedObjectContext]];

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

    if (error != nil)
    {
        [self printErrorAlert];
    }
    //THERE IS ERROR HERE
    NSManagedObject* changesGrabbed = [results objectAtIndex:0];
    NSString *changesFromDatabase = [changesGrabbed valueForKey:@"changes"];
    NSString *changesFromService = [data valueForKeyPath:@"changes"];

    if ([changesFromService isEqualToString:changesFromDatabase])
    {
        return YES;
    }
    else
    {
        [changesGrabbed setValue:changesFromService forKey:@"changes"];

        [managedObjectContext save:&error];

        if (error != nil)
        {
            [self printErrorAlert];
        }
        return NO;
    }

}

例外:

2014-06-12 21:36:12.034 MIF[437:60b] *** Terminating app due to uncaught exception     'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for     empty array'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000101cb3495 __exceptionPreprocess +     165
1   libobjc.A.dylib                     0x0000000101a1299e objc_exception_throw + 43
2   CoreFoundation                      0x0000000101c6be3f -[__NSArrayI     objectAtIndex:] + 175
3   MIF                                 0x0000000100001942 -[MIFTimetableService     isTimetableUpdatedWithJSONData:] + 514
4   MIF                                 0x000000010000219d -[MIFAppDelegate     synchrinizeTimetableService] + 157
5   MIF                                 0x0000000100001dc2 -[MIFAppDelegate     application:didFinishLaunchingWithOptions:] + 114
6   UIKit                               0x00000001005ba3d9 -[UIApplication     _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 264
7   UIKit                               0x00000001005babe1 -[UIApplication     _callInitializationDelegatesForURL:payload:suspended:] + 1605
8   UIKit                               0x00000001005bea0c -[UIApplication     _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 660
9   UIKit                               0x00000001005cfd4c -[UIApplication     handleEvent:withNewEvent:] + 3189
10  UIKit                               0x00000001005d0216 -[UIApplication     sendEvent:] + 79
11  UIKit                               0x00000001005c0086 _UIApplicationHandleEvent     + 578
12  GraphicsServices                    0x0000000103ce671a _PurpleEventCallback +     762
13  GraphicsServices                    0x0000000103ce61e1 PurpleEventCallback + 35
14  CoreFoundation                      0x0000000101c35679     __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
15  CoreFoundation                      0x0000000101c3544e __CFRunLoopDoSource1 +    478
16  CoreFoundation                      0x0000000101c5e903 __CFRunLoopRun + 1939
17  CoreFoundation                      0x0000000101c5dd83 CFRunLoopRunSpecific +     467
18  UIKit                               0x00000001005be2e1 -[UIApplication _run] +     609
19  UIKit                               0x00000001005bfe33 UIApplicationMain + 1010
20  MIF                                 0x0000000100001d23 main + 115
21  libdyld.dylib                       0x000000010234b5fd start + 1
22  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

伙计们,有人可以帮我吗?我真的需要你的帮助。谢谢。

3 个答案:

答案 0 :(得分:2)

你的麻烦制造者好像是

  

NSManagedObject * changesGrabbed = [results objectAtIndex:0];

如果结果是一个空数组,则调用 objectAtIndex:0 将导致NSRangeException,因为索引为0时没有对象。更好地调用[results firstObject],如果结果为空数组,则不会因错误而崩溃。在这种情况下,firstObject()只返回nil。

答案 1 :(得分:1)

您正在尝试从空数组中检索对象。您应该首先检查数组是否包含任何对象。使用count属性:

if (results.count > 0) {
    NSManagedObject* changesGrabbed = [results objectAtIndex:0];
    //continue...
} else {
    //Array is empty, object 0 will be beyond bounds
}

答案 2 :(得分:1)

就在

之前
NSManagedObject* changesGrabbed = [results objectAtIndex:0];

根据返回的结果添加分支。如下所示:

if (results && [results count] > 0) {
    NSManagedObject* changesGrabbed = [results objectAtIndex:0];
    ...
}

你的数组是空的。堆栈跟踪非常适合你 -

  

原因:' * - [__ NSArrayI objectAtIndex:]:超出范围的索引0   空数组'