我通过UserDefaults从我的UserDefaults发送字符串值到UserDefaults 。 但是当我通过后退按钮从vc2移回到vc1时,该值不会更新。 我在viewWillAppear方法中获得了vc1的价值。 但我的价值不会更新。 我通过推送方法从vc1导航到vc2。
这就是我如何将用户默认值存储在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()并在vc1我得到这样的viewWillAppear委托,
let count = UserDefaults.standard.string(forKey: "cartsItems") print(count)当我从vc2通过后退按钮值回到vc1时,永远不会更新,当我调用某个其他vc并再次调用vc1时,它会得到更新。 我当时如何更新价值?
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?
最满意答案
那么,正确的做法是使用简单的代理协议将数据从一个VC2传输到另一个VC1 。
以下是如何使用protocol的步骤。
在VC2 `执行以下步骤。
就在你的类声明之上宣告你的委托。
protocol MyDelegate:class { func sendDataBack(value: Int) }在class声明你的delegate一个weak variable
weak var myDelegateObj: MyDelegate?当你dismiss the VC只需要用线呼叫委托人
myDelegateObj?.sendDataBack(value: yourIntegrerValue)现在转到您的VC1并转到您已将VC1推入VC2并执行以下操作。
vc2.myDelegateObj = self // vc2 is VC2 objcet并在VC1实施您的委托方法
func sendDataBack(value: Int) { print(value) }希望这可以帮助。
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 objcetand implement the method your delegate in the VC1
func sendDataBack(value: Int) { print(value) }Hope this helps.
更多推荐
发布评论