gpt4 book ai didi

ios - 使用 MagicalRecord 有效保存

转载 作者:行者123 更新时间:2023-11-29 12:48:56 30 4
gpt4 key购买 nike

我在我的 iOS 应用程序中使用 MagicalRecord,但不确定正确的保存方式。

我的应用是关于聊天的,每次登录用户收到消息时,我都需要更新一个时间 token 。

现在我这样做:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {

    User *currentUser = [User MR_findFirstByAttribute:@"id" 
withValue:@(_CURRENT_USER_ID)
inContext:localContext];

currentUser.lastChatMessageTimeToken = [NSDate date];
}];

但是,我认为它效率不高,因为一旦用户登录,他的 id 就确定了,而 currentUser 总是相同的。

我在想我应该将 currentUser 缓存为实例变量,但找不到相应的 MagicalRecord 方法来执行。

此外,有人告诉我不要缓存 NSManagedObject,因为它绑定(bind)到上下文。

所以我不确定我应该做什么。谁能帮忙?

最佳答案

你是正确的,获取,然后更新,最后保存单个对象不是很有效。只要知道它属于哪个上下文,就可以保留对 currentUser 对象的引用。从那里,您的代码将如下所示;

currentUser = //from somewhere else, a property perhaps
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
User *localUser = [currentUser MR_inContext:localContext];
localUser.lastChatMessageTime = [NSDate date];
}];

通过对象 ID 获取对象将比执行获取请求更快。但是,由于您只更改一个对象,我建议只保存在当前线程上(只要上下文也在正确的线程上):

NSManagedObjectContext *context = //....
User *currentUser = //from somewhere, and create in the context

currentUser.lastChatMessageTime = [NSDate date];

[context MR_saveToPersistentStoreAndWait];

这样就没有要处理的 block ,而且您不必在后台队列上执行保存,因为即使在主线程上,这个单个记录更新也可能足够快。

关于ios - 使用 MagicalRecord 有效保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22899210/

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