首页 > 解决方案 > 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?

标签: iosswiftuserdefaults

解决方案


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.


推荐阅读