Swift 观察 UIApplication 属性

Swift observe UIApplication property

是否有可能以某种方式观察 swiftUIApplication.sharedApplication() 的 属性?

我需要跟踪 UIApplication.sharedApplication().applicationIconBadgeNumber 以根据该数字更新我的应用程序 UI,但无论何时更改此 属性 UI 都不会受到影响。

我的代码:

private var badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.notificationsButton.setTitle(self.badgeCount, forState: .Normal)
}

这个解决方案可能适用于您通过扩展将 iconBadgeNumber 计算变量添加到 UIApplication,它会设置真实变量并通知您的应用更改

extension UIApplication
{
  var iconBadgeNumber:Int { set{self.applicationIconBadgeNumber = iconBadgeNumber
            NSNotificationCenter.defaultCenter().postNotificationName("BageNumberChanged", object: nil)
        } get{return self.applicationIconBadgeNumber}}
}

//Add this at Observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(Controller.Method), name: "BageNumberChanged", object: nil)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.


     UIApplication.sharedApplication().applicationIconBadgeNumber = 5

    return true
}
 override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)

        let badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

        let notificationsButton: UIButton = UIButton (type: UIButtonType.Custom)

        notificationsButton.addTarget(self, action: "tapBarNotificationsButton", forControlEvents: UIControlEvents.TouchUpInside)

        notificationsButton.frame = CGRectMake(0, 0, 25, 25)

        notificationsButton.backgroundColor = UIColor.blackColor()

        notificationsButton.setTitle(badgeCount, forState: .Normal)

        let barnotificationsButton = UIBarButtonItem(customView: notificationsButton)

        self.navigationItem.setRightBarButtonItem(barnotificationsButton, animated: true)



    }