我有一个带有两个单独的 TableViewController(“TVC”)的应用程序,它们访问相同的 CoreData SQL 表。用户通过按下父 ViewController 中的按钮来调用 TVC。但是,第二个 TVC 无法识别通过第一个 TVC 调用 NSManagedObject 子类写入 CoreData 的记录。我想我正在创建 UIManagedDocument 的单独实例,因此开始在父 VC 中实例化 UIManagedDocument 并将文档传递给相应的 TVC。
但是,现在,当我在写入记录后尝试保存文档时,即使我在最初实例化文档的主线程上,应用程序也会崩溃。
我会以错误的方式解决这个问题吗?
这是父视图控制器
//
#import "ITrackViewController.h"
#import "AthleteSearchTVController.h"
@interface ITrackViewController()
@end
@implementation ITrackViewController
@synthesize myFirstName = _myFirstName;
@synthesize myLastName = _myLastName;
@synthesize athleteDatabase = _athleteDatabase;
-(void) setAthleteDatabase:(UIManagedDocument *)athleteDatabase
{
if(_athleteDatabase != athleteDatabase)
{
_athleteDatabase = athleteDatabase;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (!self.athleteDatabase) { // for demo purposes, we'll create a default database if none is set
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"Default Athlete Database"];
NSLog(@"url for dataBase is %@.",url);
// url is now "<Documents Directory>/Default Athlete Database"
self.athleteDatabase = [[UIManagedDocument alloc] initWithFileURL:url]; // setter will create this for us on disk
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"BeginSearch"]) {
NSLog(@"firstName is %@ and lastName is %@.",firstName.text, lastName.text);
NSString *checkFirstName = [firstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *checkLastName = [firstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([checkFirstName length] < 1 || [checkLastName length] < 1) {
NSLog(@"Must include a value for both first and last names.");
} else {
[self dismissKeyboard:sender];
myFirstName = firstName.text;
myLastName = lastName.text;
UIManagedDocument *sharedAthleteDataBase = [self sharedDatabase];
NSString *searchName = [myFirstName stringByAppendingString:@"%20"];
searchName = [searchName stringByAppendingString:myLastName];
NSLog(@"searchName is %@ before segue.",searchName);
[segue.destinationViewController nameToSearchFor:searchName andUIManagedDoc:sharedAthleteDataBase];
}
}
}
-(IBAction)dismissKeyboard:(id)sender
{
[lastName endEditing:YES];
[firstName endEditing:YES];
}
- (UIManagedDocument *) sharedDatabase
{
__block UIManagedDocument *managedDocument = nil;
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"AthleteData"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.athleteDatabase.fileURL path]]) {
// does not exist on disk, so create it
[self.athleteDatabase saveToURL:self.athleteDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if(success){
NSString* isMainThread;
if ([NSThread isMainThread]) {
isMainThread = @"on main thread.";
} else isMainThread = @"but not on main thread";
NSLog(@"athleteDatabase did not exist, now created %@", isMainThread);
managedDocument = self.athleteDatabase;
} else {
NSLog(@"Error creating athleteDatabase");
}
}];
} else if (self.athleteDatabase.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self.athleteDatabase openWithCompletionHandler:^(BOOL success) {
if(success){
NSString* isMainThread;
if ([NSThread isMainThread]) {
isMainThread = @"on main thread.";
} else isMainThread = @"but not on main thread";
NSLog(@"athleteDatabase was closed, is now open %@", isMainThread);
managedDocument = self.athleteDatabase;
} else NSLog(@"Error opening closed athleteDatabase");
}];
} else if (self.athleteDatabase.documentState == UIDocumentStateNormal) {
// already open and ready to use
managedDocument = self.athleteDatabase;
}
return managedDocument;
}
@end
这是调用 NSManagedObject 子类以首先从基于 Web 的 API 检索数据然后将其写入 CoreData 的 TVC。
- (void)fetchAthleteSearchResultsIntoDocument:(UIManagedDocument *)document
whereNameIs:(NSString *)athleteName
{
dispatch_queue_t fetchQ = dispatch_queue_create("Athlete fetcher", NULL);
dispatch_async(fetchQ, ^{
NSString* isMainThread;
if ([NSThread isMainThread]) {
isMainThread = @"on main thread.";
} else isMainThread = @"but not on main thread";
NSLog(@"Preparing to get records %@", isMainThread);
NSArray *athleteRecords;
athleteRecords = [AthleticNetDataFetcher searchForMyAthleteWithName:athleteName];
[document.managedObjectContext performBlockAndWait:^{ // perform in the NSMOC's safe thread (main thread)
int iCount = 0;
for (NSDictionary *athleteInfo in athleteRecords) {
[ResultsForAthleteSearch resultsWithAthleteInfo:athleteInfo inManagedObjectContext:document.managedObjectContext
numberForSorting:iCount];
iCount = iCount + 1;
// table will automatically update due to NSFetchedResultsController's observing of the NSMOC
}
NSString* isMainThread;
if ([NSThread isMainThread]) {
isMainThread = @"on main thread.";
} else isMainThread = @"but not on main thread";
NSLog(@"Preparing to save results %@", isMainThread);
[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];
}];
});
}
模拟器在调用 [document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL] 时崩溃;
下面部分给出的日志说我在主线程上。我不明白为什么这会崩溃。如果我注释掉 saveToURL 调用并依赖自动保存,它不会崩溃。
2013-10-02 13:46:22.459 iTrackTest[14989:c07] url for dataBase is file://localhost/Users/Phlipo/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/53E19DAE-6D2B-4B7F-A633-55C2BCA95AC5/Documents/Default%20Athlete%20Database/.
2013-10-02 13:46:31.031 iTrackTest[14989:c07] url for dataBase is file://localhost/Users/Phlipo/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/53E19DAE-6D2B-4B7F-A633-55C2BCA95AC5/Documents/Default%20Athlete%20Database/.
2013-10-02 13:46:31.039 iTrackTest[14989:61f] Preparing to get records but not on main thread
2013-10-02 13:46:31.065 iTrackTest[14989:c07] athleteDatabase was closed, is now open on main thread.
2013-10-02 13:46:31.620 iTrackTest[14989:61f] [AthleticNetDataFetcher executeSearchRequest:] received {
.
[A bunch of data in JSON format].
.
}
2013-10-02 13:46:31.633 iTrackTest[14989:c07] Preparing to save results on main thread.
2013-10-02 13:47:23.258 iTrackTest[16150:3f07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
我在 TVC 中实例化 MOD 时没有遇到这个 NSPErsistence 错误。也许我需要一个更明确的数据库助手?
提前感谢您的帮助。