我这在进行SwiftUI开发,使用CoreData,我有一个Friend类型,和ChatHistory具有一对多关系。我想在View中使用@FetchRequest获取特定Friend所绑定的ChatHistory数组
时间: 2024-03-06 11:46:24 浏览: 36
可以通过在 `@FetchRequest` 中添加一个 `NSPredicate` 来获取特定 Friend 所关联的 ChatHistory 数组。具体实现如下:
首先,在你的 `Friend` 实体中添加一个 `toChatHistory` 的关系,表示一个 Friend 对应多个 ChatHistory。在 `ChatHistory` 实体中添加一个 `fromFriend` 的关系,表示一个 ChatHistory 对应一个 Friend。
然后在你的 View 中创建一个 `@FetchRequest`,并添加一个 `NSPredicate`,这个 `NSPredicate` 用来筛选出特定 Friend 关联的 ChatHistory。下面是一个简单的示例代码,假设我们要获取 `friend` 对应的 ChatHistory 数组:
```
struct FriendChatHistoryView: View {
@Environment(\.managedObjectContext) private var viewContext
// 这里的 friend 是传入的 Friend 实例
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \ChatHistory.timestamp, ascending: true)],
predicate: NSPredicate(format: "fromFriend == %@", friend)
) var chatHistory: FetchedResults<ChatHistory>
var body: some View {
ForEach(chatHistory) { history in
// 使用 ChatHistory 实例渲染 View
}
}
}
```
在上面的代码中,我们创建了一个 `@FetchRequest`,并通过 `NSPredicate` 来筛选出 `fromFriend` 关系为 `friend` 的 ChatHistory 实例。然后我们可以使用这个 `chatHistory` 数组来在 View 中渲染 ChatHistory 列表。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)