将实体属性数据保存到核心数据后如何保存

时间:2018-09-20 01:26:04

标签: ios swift core-data

我正在创建UserEntity的实体

    let userEntity = UserEntity(context: managedContext)

    userEntity.username = user.username
    userEntity.name = user.name
    userEntity.personCode = user.personCode
    userEntity.personalData = XMLRegistrationData.toEntity(userPersonalData: user.registrations.registrationData)

并将其保存在此属性“ loggedUser”中:

            let loggedUser = XMLUserData.toEntity(user: xmlUserData)
            print(loggedUser) // first print

            do {
                try self.context.save()

                print(loggedUser) // second print
            } catch {
                ...
            }

第一个打印结果是这样的:

<UserEntity: 0x282b07a70> (entity: UserEntity; id: 0x28081c460 <x-coredata:///UserEntity/t78B51567-8104-4232-9BEA-062FBCB3CEEC3> ; data: {
    activeSession = nil;
    name = "FOO";
    personCode = 000;
    personalData = "0x280828020 <x-coredata:///UserPersonalDataEntity/t78B51567-8104-4232-9BEA-062FBCB3CEEC4>";
    username = 001;
})

但是第二个打印结果是这样的:

<UserEntity: 0x282b07a70> (entity: UserEntity; id: 0xd000000000840002 <x-coredata://C833ECD4-5D54-48C3-9860-B2E0781D08EC/UserEntity/p33> ; data: <fault>)

将UserEntity属性保存到核心数据后为nil。该对象保存在核心数据上,我可以使用context.fetch来获取它,但是loggingUser被更改了。

为什么会发生?保存后如何将数据保留在loggingUser上,而不必在保存后从核心数据中获取数据?

1 个答案:

答案 0 :(得分:0)

不是nil,而是fault。数据仍然在那里。您可以通过打印loggedUser.username

来证明这一点
  

故障转移通过将占位符对象(错误)保留在持久性存储中来减少应用程序的内存使用。

相关问题