gpt4 book ai didi

ios - NSManagedObjectContext 保存似乎丢失对象

转载 作者:行者123 更新时间:2023-11-29 13:17:40 26 4
gpt4 key购买 nike

我正在使用以下代码创建一个对象:

 +(Checkin *) newCheckinWithId:(NSString*) checkinID forVenueId:(NSString *)venueId
{
NSManagedObjectContext * context = [[AppDelegate sharedInstance] managedObjectContext];
Checkin *ret = (Checkin *)[NSEntityDescription insertNewObjectForEntityForName:@"Checkin" inManagedObjectContext:context];
ret.checkinID = checkinID;
ret.forVenueID = venueId;
ret.date = [NSDate date];
NSError * error;
if(![context save:&error]) {
NSLog(@"Error saving!!!!!: %@", error.userInfo);
}
return ret;
}

并且没有错误,但是在保存之后我再也没有看到那个对象的任何记录。

在这个函数上运行调试器,我看到它在 unprocessedInserts 中有 1 个对象,并且在上下文中的所有内部集合中保存 0 个对象之后(我不确定这是否是预期的。

这是我用来创建我的商店 + 托管对象上下文的代码(我对所有内容都使用 1 个上下文)它基本上全部来 self 发现的堆栈溢出帖子

- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil)
{
return _managedObjectModel;
}
//NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
//__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

//NSArray *testArray = [[NSBundle mainBundle] URLsForResourcesWithExtension:@"momd"subdirectory:nil];

NSString *path = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"momd"];

if( !path ) path = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"mom"];

NSURL *modelURL = [NSURL fileURLWithPath:path];

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

//__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if((_persistentStoreCoordinator != nil)) {
return _persistentStoreCoordinator;
}

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSPersistentStoreCoordinator *psc = _persistentStoreCoordinator;

// Set up iCloud in another thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// ** Note: if you adapt this code for your own use, you MUST change this variable:
NSString *iCloudEnabledAppID = @"[MY APP ID]";

// ** Note: if you adapt this code for your own use, you should change this variable:
NSString *dataFileName = @"foursquareaugmentation.sqlite";

// ** Note: For basic usage you shouldn't need to change anything else

NSString *iCloudDataDirectoryName = @"Data.nosync";
NSString *iCloudLogsDirectoryName = @"Logs";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];

if (iCloud) {

NSLog(@"iCloud is working");

NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];

NSLog(@"iCloudEnabledAppID = %@",iCloudEnabledAppID);
NSLog(@"dataFileName = %@", dataFileName);
NSLog(@"iCloudDataDirectoryName = %@", iCloudDataDirectoryName);
NSLog(@"iCloudLogsDirectoryName = %@", iCloudLogsDirectoryName);
NSLog(@"iCloud = %@", iCloud);
NSLog(@"iCloudLogsPath = %@", iCloudLogsPath);

if([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
NSError *fileSystemError;
[fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&fileSystemError];
if(fileSystemError != nil) {
NSLog(@"Error creating database directory %@", fileSystemError);
}
}

NSString *iCloudData = [[[iCloud path]
stringByAppendingPathComponent:iCloudDataDirectoryName]
stringByAppendingPathComponent:dataFileName];

NSLog(@"iCloudData = %@", iCloudData);

NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:iCloudEnabledAppID forKey:NSPersistentStoreUbiquitousContentNameKey];
[options setObject:iCloudLogsPath forKey:NSPersistentStoreUbiquitousContentURLKey];

[psc lock];
NSError *error;

[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[NSURL fileURLWithPath:iCloudData]
options:options
error:&error];

if( error )
{
NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);

// comment in this line while debugging if get "Can't find model for source store" error in addPersistentStoreWithType.
// it means the sqlite database doesn't match the new model and needs to be created from scratch.
// this happens if you change the xcdatamodel instead of creating a new one under Xcode->Editor->Add Model Version...
// CoreData can only automatically migrate if there is a new model version (it can't migrate if the model simply changes, because it can't see the difference between the two models).
// be sure to back up the database if needed, because all data will be lost.
//[fileManager removeItemAtPath:iCloudData error:&error];

/*// this is another way to verify the hashes for the database's model to make sure they match one of the entries in the momd directory's VersionInfo.plist
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:[NSURL fileURLWithPath:iCloudData] error:&error];

if( !sourceMetadata )
NSLog(@"sourceMetadata is nil");
else
NSLog(@"sourceMetadata is %@", sourceMetadata);*/
}

[psc unlock];
}
else {
NSLog(@"iCloud is NOT working - using a local store");
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

[psc lock];
NSError *error;

[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:localStore
options:options
error:nil];

if( error )
NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);
[psc unlock];
}

dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"SomethingChanged" object:self userInfo:nil];
});
});

return _persistentStoreCoordinator;
}

/*
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *) managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return _managedObjectContext;
}

我已经在这方面安静地工作了一段时间,并且没有什么可以尝试的,所以任何帮助或调试步骤都将不胜感激。 (它也不适用于 icloud 或本地)

也许我获取错误,这就是我没有获取对象的原因。这是我的提取:

+(NSArray *) checkinsForVenue:(NSString *) venueID
{
NSManagedObjectContext * context = [[AppDelegate sharedInstance] managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Checkin" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;

//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(forVenueID = %@)", venueID];
//request.predicate = predicate;

NSError *error;
NSArray * ret = [context executeFetchRequest:request error:&error];
if(ret == nil) {
NSLog(@"%@", error.description);
}
return ret;
}

编辑:我问错了问题。保存是有效的,提取不是。仍然无法弄清楚我的提取有什么问题。

最佳答案

您是否检查过它是否真的被持久化到 sqlite?

您的应用程序应该在 ~Library/Application Support/iPhone Simulator/6.1/Applications 中。您必须找到属于您的应用程序文件夹(它们都是由 UUIDS 命名的),然后在 Documents 文件夹中查找 sqlite 文件。在您的代码中,它是 foursquareaugmentation.sqlite

在该目录中打开终端窗口并启动 sqlite3 foursquareaugmentation.sqlite 以开始查询数据库。

你应该找到一个名为 ZCHECKIN 的表(如果你有一个名为 Checkin 的托管对象类),并且每次你保存上下文时,它应该添加到那个表。

因此在每次保存后运行 select * from zcheckin; 应该会显示该表中又添加了一行。

如果这没有发生,则 save 操作出现问题。如果它在数据库表中,那么它是您的代码中的某些东西丢失了对该对象的引用,将其设置为 nil 某处,或类似的东西。

希望对您有所帮助。

关于ios - NSManagedObjectContext 保存似乎丢失对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com