gpt4 book ai didi

ios - 是否可以为 CoreData 中的一对多关系使用有损耦合类? (类似于 Android Room ORM 中的 @Embedded)

转载 作者:行者123 更新时间:2023-11-29 11:24:47 25 4
gpt4 key购买 nike

我正在阅读 CoreData 的一对多关系教程 - https://cocoacasts.com/one-to-many-and-many-to-many-core-data-relationships/

  1. 一个帐户可以有多个用户
  2. 每个用户可以有一个帐户

在本教程中,我们最终得到了彼此紧密耦合的类。

  1. Account 具有作为类成员的 User 列表。
  2. UserAccount 作为类(class)成员。

如何在Android中实现有损耦合

在 Android Room(Android 的 ORM 库)中,我们能够避免这种紧耦合的类设计。我们将有另一个“容器”类,它包含 Account 对象和 User 对象列表。

此解决方案的关键是使用 @Embedded功能。

public class AccountWithUser {
@Embedded
public Account account;

@Relation(parentColumn = "id", entityColumn = "accountId", entity = User.class)
public List<User> users;
}

@Entity(tableName = "account")
public class Account {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public int id;
}

@Entity(tableName = "user")
public class User {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public int id;

@ColumnInfo(name = "account_id")
public int accountId;

@ColumnInfo(name = "first_name")
public int firstName;

@ColumnInfo(name = "last_name")
public long lastName;
}

如果我们查看生成的 SQLite 表,它看起来如下

账户表

enter image description here

用户表

enter image description here

从上面的 Android 设计中,您可以看到 AccountUser 类是非常有损耦合的。


我在想,CoreData有没有类似的@Embedded特性,这样我们就可以实现一对多关系的lossy coupled类?

最佳答案

我在 Android ORM 方面没有太多经验,但是为 2 个 SQL 表使用 3 个类似乎是一个很大的不便。最流行的 Hibernate ORM 则相反,对于多对多关系,您为 3 个 SQL 表创建 2 个类。

https://www.baeldung.com/hibernate-many-to-many

我在这里检查了 Room ORM 的推理: https://developer.android.com/training/data-storage/room/referencing-data#understand-no-object-references

这个“限制”似乎是为了防止开发人员出现性能或内存问题。

However, this seemingly innocent change causes the Author table to be queried on the main thread.

这在 iOS 中很常见,访问数据库以获取延迟加载的相关对象以填充 TableView 中的行。表中大部分行的创建都是在

tableView(_:cellForRowAt:)

https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614861-tableview

我相信它不会在主线程中运行。

大多数时候只有在加载图像时才需要某种后台加载,从外部加载一些东西,然后我们将使用 DispatchQueue

https://nghiatran.me/advanced-issues-the-right-way-to-load-content-in-backgrounds-thread-with-tableview/

关于ios - 是否可以为 CoreData 中的一对多关系使用有损耦合类? (类似于 Android Room ORM 中的 @Embedded),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59495239/

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