核心数据引发了获取异常

时间:2015-07-23 08:45:07

标签: ios objective-c core-data

我的iOS应用程序在执行保存操作之前检查实体是否存在。

@implementation DataPrice


+ (NSString*)entityName
{
    return @"Price";
}


+ (instancetype)fetchDataPriceInManagedObjectContext:(NSManagedObjectContext *)managedObjectContext {
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Price" inManagedObjectContext:managedObjectContext];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"postDate" ascending:YES];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    request.sortDescriptors = @[ sortDescriptor ];
    request.fetchLimit = 1;

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

    DataPrice *result = fetchResults.firstObject;

    return result;
}

运行代码会引发以下异常:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
*** First throw call stack:
(
    0   CoreFoundation                      0x01497946 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x01120a97 objc_exception_throw + 44
    2   CoreData                            0x004ce33e -[NSManagedObjectContext executeFetchRequest:error:] + 5230
    3   DenkoStation                        0x000395d3 +[DataPrice fetchDataPriceInManagedObjectContext:] + 499
    4   DenkoStation                        0x00038ccb -[ViewController updateLocalPrice:] + 219
    5   DenkoStation                        0x000387a2 __52-[ViewController displayInternetConnectivityMessage]_block_invoke_3 + 1490
    6   DenkoStation                        0x000df531 __66-[RKObjectRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke248 + 97
    7   libdispatch.dylib                   0x0319b30a _dispatch_call_block_and_release + 15
    8   libdispatch.dylib                   0x031bbe2f _dispatch_client_callout + 14
    9   libdispatch.dylib                   0x031a290e _dispatch_main_queue_callback_4CF + 606
    10  CoreFoundation                      0x013f195e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    11  CoreFoundation                      0x013b0760 __CFRunLoopRun + 2256
    12  CoreFoundation                      0x013afbcb CFRunLoopRunSpecific + 443
    13  CoreFoundation                      0x013af9fb CFRunLoopRunInMode + 123
    14  GraphicsServices                    0x04fa824f GSEventRunModal + 192
    15  GraphicsServices                    0x04fa808c GSEventRun + 104
    16  UIKit                               0x01a5e8b6 UIApplicationMain + 1526
    17  DenkoStation                        0x00039e0d main + 141
    18  libdyld.dylib                       0x031e7ac9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我的猜测是Core Data抱怨,因为记录Price不存在。

有解决方法吗?

0 个答案:

没有答案