2

I am building a ViewController in Swift to update when state changes occur from an Objective-C class. Others have written the ObjC; I am implementing the Swift view.

While conceptually aware of NSNotification, Delegates and Callbacks 1, I am looking to employ Key-Value Observing (KVO).

Apple has overview documentation of KVOs 2 and for Swift 3. Others have documented in Swift 4 and ObjC 5 seperately, but it is still not clear how to implement KVO with a mixed Swift/ObjC environment.

Unclear after reading through the previous StackOverflow discussion on this. Is key-value observation (KVO) available in Swift?

It is understood that the Swift object is the Observer and the ObjC object to be the Observed. Also understood that the Observer inherits from NSObject.

I am looking to have the Swift ViewController, specifically the lastUpdate variable, to be updated each time the ObjC instance variable, lastRealTimeSynchronizeDate, changes.

And still uncertain how and to express the dependencies on the property I want to observe, where and how to create the global context variable and how the observer for the key path works.

Sample code attached below where KVO has yet to be implemented.

Any guidance would be appreciated. Thank you

SynchronizeMgr.m below:

- (void)synchronizeCompleted
{
    // standard date formatting
    NSDate *now = [NSDate date];
    NSString *dateString = [NSDateFormatter localizedStringFromDate:now
                                                          dateStyle:NSDateFormatterShortStyle
                                                          timeStyle:NSDateFormatterShortStyle];        

    // want Swift ViewController, lastUpdate, to be updated each time this ivar changes
    _lastRealTimeSynchronizeDate = dateString;
}

SynchronizeStatus.swift below:

class SynchronizeStatusViewController: UIViewController {

    @IBOutlet weak var lastUpdate: UILabel!

    func pullDate() -> String  {

        // retrieving from ObjC, lastRealTimeSynchronizeDate via sharedManager
        let m = SynchronizeMgr.sharedManager()
        let d = m.lastRealTimeSynchronizeDate

        if d == nil {

            return "nil"

        } else {

            return d

        }            
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // looking to have this update whenever lastRealTimeSynchronizeDate in ObjC is updated
        lastUpdate.text = pullDate()

    }  
}
Community
  • 1
  • 1
bucephalus
  • 89
  • 1
  • 5
  • Note: was unable to provide links, so the URLs are intentionally broken to document all known informative sources. Apologies in advance. – bucephalus Jan 05 '16 at 20:23

0 Answers0