ios - Issue in updating value from `UserDefaults` in Swift
问题描述
I'm sending a string value from my vc2 to vc1 through UserDefaults
. But when I move back to vc1 from vc2 through back button the value doesn't update. I'm getting value in vc1 in viewWillAppear
method. But my value does not update. I navigate from vc1 to vc2 through push method.
This is how i stored the value in user default in vc2,
cartItems = cartItems + 1
print(cartItems)
let badgeCount = String(cartItems)
print(badgeCount)
let rightBarButton = self.navigationItem.rightBarButtonItem
let badge = String(badgeCount)
rightBarButton?.addBadge(text: badge)
UserDefaults.standard.set(badgeCount, forKey: "cartsItems")
UserDefaults.standard.synchronize()
and in vc1 i get like this in viewWillAppear delegate,
let count = UserDefaults.standard.string(forKey: "cartsItems")
print(count)
When i come back to vc1 from vc2 through back button value never update and when i call some other vc and than call again vc1 it gets update. How can i update value at that time?
解决方案
Well, the proper way to do this is with a simple delegate protocol to transfer data from one VC2
to another VC1
.
Below are the steps how to work with the protocol
.
In VC2
` do the following steps.
Just above your class declaration declare your delegate.
protocol MyDelegate:class {
func sendDataBack(value: Int)
}
In class
declare a weak variable
of your delegate
weak var myDelegateObj: MyDelegate?
and when you dismiss the VC
just call the delegate with line
myDelegateObj?.sendDataBack(value: yourIntegrerValue)
Now go to your VC1
and go to the line where you have pushed VC1
to VC2
and do the following.
vc2.myDelegateObj = self // vc2 is VC2 objcet
and implement the method your delegate in the VC1
func sendDataBack(value: Int) {
print(value)
}
Hope this helps.
推荐阅读
- reactjs - React TypeScript - 传递回调函数
- javascript - 将响应正文 blob 转换为 json 或 javascript 中的纯文本
- python-3.x - FileNotFoundError: [Errno 2] No such file or directory -- 即使我使用的是完整路径
- javascript - 如何使用猫鼬将 JSON 中的对象保存在不同的文档中?
- amazon-web-services - 如何处理乱序的微服务消息?
- python - 如何使用来自 pandas 另一列的 unicode 文本创建新列?
- javascript - 从外部访问在 JavaScript switch 语句中声明的变量
- nlp - 有任何实际使用(非训练)预训练 BERT 模型进行 NER 的例子吗?
- java - 数组返回不正确的索引?
- javascript - 为什么这个递归展平数组函数会给我错误的结果?Javascript