我正在尝试在 iOS 7 应用程序中实现 Core Data(并且之前已成功完成)。但是,当我执行 executeFetchRequest 方法时,应用程序崩溃了。最相关的代码添加如下:
#import "JTHuntingSeasonDB.h"
@implementation JTHuntingSeasonDB
- (id)init {
self = [super init];
if (self) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"JTHuntingDB";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
document = [[UIManagedDocument alloc] initWithFileURL:url];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];
if (fileExists) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(@"Document opened successfully");
self.allSpecies = [self getSpecies];
self.speciesToday = [self getSpeciesToday];
} else NSLog(@"Failed to open document");
}];
} else {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(@"Document created successfully");
self.allSpecies = [self getSpecies];
self.speciesToday = [self getSpeciesToday];
} else NSLog(@"Failed to create document, path: %@", url);
}];
}
}
return self;
}
#pragma mark - Core Data
- (NSArray *)getSpecies {
if (document.documentState == UIDocumentStateNormal) {
context = document.managedObjectContext;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *country = [defaults stringForKey:@"Country"];
NSString *subregion = [defaults stringForKey:@"Subregion"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"HuntingDates"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedStandardCompare:)];
request.fetchBatchSize = 150;
request.fetchLimit = 150;
request.sortDescriptors = @[sortDescriptor];
if (subregion.length > 0) {
request.predicate = [NSPredicate predicateWithFormat:@"(country IN %@) AND (subregion IN %@)", country, subregion];
} else {
request.predicate = [NSPredicate predicateWithFormat:@"country IN %@", country];
}
NSError *error;
return [context executeFetchRequest:request error:&error];
}
return nil;
}
线
return [context executeFetchRequest:request error:&error];
导致应用程序崩溃。这是我到目前为止所做和发现的:
- 模拟器:删除应用程序并重置内容和设置
- Xcode:清洁(构建文件夹)
- “上下文”不是零
- NSLog 打印出“文档创建/打开成功”
- 当应用程序崩溃时,控制台中只打印“lldb”
编辑: 在遵循 Wain 的建议后,我关闭了异常断点,收到一条更具描述性的错误消息,指出谓词无效。通过将谓词中的 IN 替换为 CONTAINS 并更改变量“country”以使其不再返回 nil 来解决问题。