gpt4 book ai didi

iphone - 一些 CoreData 关系在关闭应用程序后丢失

转载 作者:太空狗 更新时间:2023-10-30 03:28:13 25 4
gpt4 key购买 nike

这是我的问题的概述:

我正在添加(并确认它们已添加)大约 1400 个从 soap 服务加载到 CoreDat 中的关系。在我关闭应用程序并再次打开后,一些关系丢失了;我只看到大约 800 个(尽管有所不同)。另外,我没有收到任何错误。

现在,更多细节:

我有一个名为 User 的对象,其中包含有关用户已保存的服务的信息;它看起来像这样:

@interface OosUser : NSManagedObject

+ (OosUser *) userFromSlug: (NSString *) slug;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *slug;
@property (nonatomic, retain) NSMutableSet /* Service */ *services;
- (void) addServicesObject: (Service * )service;
- (void) removeServicesObject: (Service *) service;

@end

@implementation User

@dynamic name;
@dynamic slug;
@dynamic services;

static NSString *fetchPredicate = @"slug = %@";

+ (User *) userFromSlug:(NSString *)slug
{
User *result = [super objectWithPredicate: fetchPredicate, slug];
if (!result) {
result = [super create];
result.slug = slug;
}
return result;
}

@end

在使用数据的代码部分,关系是这样保存的:

NSMutableSet *userServices = self.user.services;

for (Service *service in servicesToAdd) {
[self.services addObject: service];
bool contained = false;
for (Service *userService in userServices) {
if ((contained = [userService.slug isEqualToString:service.slug])) {
break;
}
}
if (!contained) {
// [userServices addObject:service];
[self.user addServicesObject: service];
NSError *error = nil;
if (![[service managedObjectContext] save:&error]) {
NSLog(@"Saving failed");
NSLog(@"Error: %@", [error localizedDescription]);
}else {
NSLog(@"Registered service %d: %@", self.services.count, service.slug);
}
}
}

情况是我已经用调试器检查过,我可以看到添加了所有超过 1400 个关系,但是当应用程序被重置并且它们通过 self.user.services 恢复时,我只得到大约 800 个对象。

为什么会这样?有人以前有过这个吗?

提前致谢。


更新:

人们一直暗示我没有正确使用 Core Data,但问题是数据在重新启动应用程序后丢失了。使用它时绝对没有问题。我使用 Core Data 是正确的,因为它可以提供您从 Apple 获得的有限文档和示例。

最佳答案

NSMutableSet *userServices = self.user.services;

...

[userServices addObject:service];

不能那样做。 self.user.services 不返回可变集。这就是 addServicesObject 方法的用途。将第二行改为:

            [self.user addServicesObject:service];

来自 Apple 文档:

It is important to understand the difference between the values returned by the dot accessor and by mutableSetValueForKey:. mutableSetValueForKey: returns a mutable proxy object. If you mutate its contents, it will emit the appropriate key-value observing (KVO) change notifications for the relationship. The dot accessor simply returns a set. If you manipulate the set as shown in this code fragment:

[aDepartment.employees addObject:newEmployee]; // do not do this!
then KVO change notifications are not emitted and the inverse relationship is not updated correctly.

Recall that the dot simply invokes the accessor method, so for the same reasons:

[[aDepartment employees] addObject:newEmployee]; // do not do this, either!

关于iphone - 一些 CoreData 关系在关闭应用程序后丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8587330/

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