我有一个小型 Apollo iOS 应用程序的以下设置,我在表格视图中显示会议列表并希望能够将会议添加到列表中:
GraphQL:
query AllConferences {
allConferences {
...ConferenceDetails
}
}
mutation CreateConference($name: String!, $city: String!, $year: String!) {
createConference(name: $name, city: $city, year: $year) {
...ConferenceDetails
}
}
fragment ConferenceDetails on Conference {
id
name
city
year
attendees {
...AttendeeDetails
}
}
fragment AttendeeDetails on Attendee {
id
name
conferences {
id
}
}
会议表视图控制器:
class ConferencesTableViewController: UITableViewController {
var allConferencesWatcher: GraphQLQueryWatcher<AllConferencesQuery>?
var conferences: [ConferenceDetails] = [] {
didSet {
tableView.reloadData()
}
}
deinit {
allConferencesWatcher?.cancel()
}
override func viewDidLoad() {
super.viewDidLoad()
allConferencesWatcher = apollo.watch(query: AllConferencesQuery()) { result, error in
print("Updating conferences: ", result?.data?.allConferences)
guard let conferences = result?.data?.allConferences else {
return
}
self.conferences = conferences.map { $0.fragments.conferenceDetails }
}
}
// ...
// standard implementation of UITableViewDelegate
// ...
}
添加会议视图控制器:
class AddConferenceViewController: UIViewController {
// ... IBOutlets
@IBAction func saveButtonPressed() {
let name = nameTextField.text!
let city = cityTextField.text!
let year = yearTextField.text!
apollo.perform(mutation: CreateConferenceMutation(name: name, city: city, year: year)) { result, error in
if let _ = result?.data?.createConference {
self.presentingViewController?.dismiss(animated: true)
}
}
}
}
我也在cacheKeyForObject
AppDelegate 中像这样实现:
apollo.cacheKeyForObject = { $0["id"] }
我的问题是是否可以通过此设置从自动 UI 更新中受益?当前CreateConferenceMutation
执行时,表视图不会更新。我是否遗漏了什么,或者我是否达到了文档中提到的限制:
在某些情况下,仅仅使用
cacheKeyFromObject
还不足以让您的应用程序 UI 正确更新。例如,如果您想在不重新获取整个列表的情况下将某些内容添加到对象列表中,或者如果您无法为某些对象分配对象标识符,则 Apollo 无法自动为您更新现有查询。