I want to add an observer to check changes of a global variable, but it not seems possible.
var selectedItem: NSManagedObject?
class LCCC: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// need to set up an "observer" that trigger selectedItemDidChange method, if selectedItem changed
}
func selectedItemDidChange {
}
}
I think the most idiomatic way to do this in swift would be using property observers:
var test:NSString = "hi" {
willSet {
}
didSet {
}
}
(Although you need to provide an initializer)
Have you tried something like:
NSNotificationCenter.defaultCenter().addObserver(selectedItem, selector: Selector("selectedItemDidChange"), name: "selectedItemObserver", object: self)
Related
I need to track the update in a variable of struct type.
Is it possible to add an observer on struct variable in Swift?
Example:
struct MyCustomStruct {
var error:Error?
var someVar:String?
}
class MyClass{
var myCustomStruct:MyCustomStruct?
}
I want to add an observer on myCustomStruct variable.
The standard Swift “property observers” (didSet and willSet) are designed to let a type observe changes to its own properties, but not for letting external objects add their own observers. And KVO, which does support external observers, is only for dynamic and #objc properties NSObject subclasses (as outlined in Using Key-Value Observing in Swift).
So, if you want to have an external object observe changes within a struct, as others have pointed out, you have to create your own observer mechanism using Swift didSet and the like. But rather than implementing that yourself, property by property, you can write a generic type to do this for you. E.g.,
struct Observable<T> {
typealias Observer = String
private var handlers: [Observer: (T) -> Void] = [:]
var value: T {
didSet {
handlers.forEach { $0.value(value) }
}
}
init(_ value: T) {
self.value = value
}
#discardableResult
mutating func observeNext(_ handler: #escaping (T) -> Void) -> Observer {
let key = UUID().uuidString as Observer
handlers[key] = handler
return key
}
mutating func remove(_ key: Observer) {
handlers.removeValue(forKey: key)
}
}
Then you can do things like:
struct Foo {
var i: Observable<Int>
var text: Observable<String>
init(i: Int, text: String) {
self.i = Observable(i)
self.text = Observable(text)
}
}
class MyClass {
var foo: Foo
init() {
foo = Foo(i: 0, text: "foo")
}
}
let object = MyClass()
object.foo.i.observeNext { [weak self] value in // the weak reference is really only needed if you reference self, but if you do, make sure to make it weak to avoid strong reference cycle
print("new value", value)
}
And then, when you update the property, for example like below, your observer handler closure will be called:
object.foo.i.value = 42
It’s worth noting that frameworks like Bond or RxSwift offer this sort of functionality, plus a lot more.
With variables you can use two default observers
willSet - represents moment before variable will be set with new value
didSet - represents moment when variable was set
Also in observer you can work with two values. With current variable in current state, and with constant depending on observer
struct Struct {
var variable: String {
willSet {
variable // before set
newValue // after set, immutable
}
didSet {
oldValue // before set, immutable
variable // after set
}
}
}
And the same you can do for any other stored property, so you can use it for struct variable in your class too
class Class {
var myStruct: Struct? {
didSet {
...
}
}
}
Also you can for example in did set observer of variable post notification with certain name
didSet {
NotificationCenter.default.post(name: Notification.Name("VariableSet"), object: nil)
}
and then you can add certain class as observer for notification with this name
class Class {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(variableSet), name: Notification.Name("VariableSet"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("VariableSet"), object: nil)
}
#objc func variableSet() {
...
}
}
Try this, first create a struct with an action variable and when you create an object of the struct set the action parameter on the action you want. ex.
struct testStruct {
var action: (()->())?
var variable: String? {
didSet {
self.action?()
}
}
}
And inside your main code - main class
var testS = testStruct()
testS.action = {
print("Hello")
}
testS.variable = "Hi"
When you set the testS.variabe = "Hi" it will call the print("Hello")
struct MyCustomStruct {
var error:Error?
var someVar:String?
}
class MyClass{
var myCustomStruct:MyCustomStruct? {
didSet{
print("my coustomeSruct changed")
}
}
}
let aClass = MyClass()
aClass.myCustomStruct?.someVar = " test"
//prints:my coustomeSruct changed
I'm learning the State Pattern (Finite State Machine)
In the sample project that I built the only way that I figured out to update the UI is to pass a reference of the presenting view to the state machine, and then update the UI from the state I'm working. Am I doing it wrong?😕
Here's my State Machine
class CapturePhotoStateMachine {
var noPictureTakenState: NoPictureTakenState?
var pictureTakenState: PictureTakenState?
var initialState: InitialState?
var vc: SignupAvatarView?
var capturePhotoState: CapturePhotoState?
init(viewController: SignupAvatarView) {
noPictureTakenState = NoPictureTakenState(stateMachine: self)
pictureTakenState = PictureTakenState(stateMachine: self)
initialState = InitialState(stateMachine: self)
vc = viewController
capturePhotoState = initialState
}
func setCapturePhotoState(newState: CapturePhotoState) {
self.capturePhotoState = newState
}
func takePicture() {
self.capturePhotoState?.takePicture()
}
func savePicture(image: UIImage) {
self.capturePhotoState?.savePicture(image: image)
}
func retakePicture() {
self.capturePhotoState?.retakePicture()
}
func setup() {
self.capturePhotoState?.setup()
}
}
Here's my protocol
protocol CapturePhotoState {
func takePicture()
func savePicture(image: UIImage)
func retakePicture()
func setup()
}
Here's a subclass of state
class NoPictureTakenState: CapturePhotoState {
var stateMachine: CapturePhotoStateMachine?
init(stateMachine: CapturePhotoStateMachine) {
self.stateMachine = stateMachine
}
func takePicture() {
stateMachine!.vc?.previewView.isHidden = true
stateMachine!.vc?.capturedImage.isHidden = false
stateMachine!.vc?.saveButton.isHidden = false
stateMachine!.vc?.retakePhoto.isHidden = false
stateMachine?.setCapturePhotoState(newState: (stateMachine?.pictureTakenState)!)
}
func savePicture(image: UIImage) {
}
func retakePicture() {}
func setup() {}
}
The key to your state machine's purpose seems to be that you have interface objects you want to enable or disable depending on the state. That enablement / disablement should be the job of the view controller. The state itself is simply the basis on which questions can be answered such as "What is the current situation" and "What should happen next".
Here's a short simple state machine example that illustrates. It is deliberately trivial. We have just two buttons, and just two states; in each state, exactly one button should be enabled. The states are represented by cases of an enum, and we use a setter observer on that enum to respond whenever the state changes. The enum encapsulates the logic of how many states there are and what the next state is, while the view controller mediates between state change and interface change:
class ViewController: UIViewController {
#IBOutlet weak var takePictureButton: UIButton!
#IBOutlet weak var deletePictureButton: UIButton!
#IBOutlet weak var pictureImageView: UIImageView! // not used in the example
#IBAction func doTakePicture(_ sender: Any) {
// do stuff
doNextState()
}
#IBAction func doDeletePicture(_ sender: Any) {
// do stuff
doNextState()
}
enum State {
case pictureNotTaken
case pictureTaken
var nextState : State {
switch self {
case .pictureNotTaken:
return .pictureTaken
case .pictureTaken:
return .pictureNotTaken
}
}
}
var state : State = .pictureNotTaken {
didSet {
updateInterface()
}
}
func doNextState() {
self.state = self.state.nextState // triggers the setter observer
}
func updateInterface() {
switch state {
case .pictureNotTaken:
takePictureButton.isEnabled = true
deletePictureButton.isEnabled = false
case .pictureTaken:
takePictureButton.isEnabled = false
deletePictureButton.isEnabled = true
}
}
}
Probably what you want is some expansion of that pattern.
the only way that I figured out to update the UI is to pass a reference of the presenting view to the state machine
That is what the above pattern does not do. The setter observer solves that problem for us.
Now, you might object that the switch statement in updateInterface is doing the wrong kind of work. It locates the knowledge of how the interface reflects the state entirely in the view controller. Your impulse is to say that surely that knowledge is part of the state (and that's why you constructed your code the way you did).
My reply would be: well, yes and no. I do sometimes feel that way, and the way I solve the problem is to endow the state machine with properties expressing all the questions the view controller might have about what the current state means as regards the interface. That way, the knowledge is moved to the state, but the interface is still governed, correctly, by the view controller.
So, for example, we might add these two properties to our State enum:
enum State {
// ... everything else is as before ...
var userCanTakePicture : Bool { return self == .pictureNotTaken }
var userCanDeletePicture : Bool { return self == .pictureTaken }
}
So, now, our updateInterface doesn't need any special knowledge about what each state means; it merely asks the state what the interface should be, which is simpler and gives perhaps a more satisfying separation of powers:
func updateInterface() {
self.takePictureButton.isEnabled = state.userCanTakePicture
self.deletePictureButton.isEnabled = state.userCanDeletePicture
}
I have a singleton to store some global data for my macOS app, one of my ViewController keeps modifying data. I want to simultaneously show the changes in a View, which is related to another ViewController. what 's the best way to do this?
Global Data:
final class AppData {
static var logs: [LogData] = []
}
ViewController 1:
class FirstViewController: NSViewController {
AppData.logs.append(newLogData)
}
ViewController 2:
class SecondViewController: NSViewController {
// what's the best way to simultaneously watch the change of AppData.logs?
}
If your App is planned to be macOS only you can use a NSObjectController. This is definitively the easiest approach and you can do most of the configuration in Interface builder. It works internally with bindings. In case of an array you want to observe, you would use a NSArrayController.
One way is to use the notificationcenter
In viewcontroller2 add:
override func viewDidLoad() {
super.viewDidLoad()
notificationCenter.default.addObserver(self,
selector: #selector(view1DidChange),
name: "view1DidChange",
object: nil
)
}
#objc private func view1DidChange(_ notification: Notification) {
// Do something
}
In viewcontroller1 add
notificationCenter.default.post(name: "view1DidChange", object: self)
This can be repeated in every class, that should listen.
Here i am sharing the Delegate & Protocol approach to achieve this functionality.
final class AppData {
static var logs: [LogData] = []
}
protocol FirstViewControllerDelegate {
func ViewControllerDelegate(appData:[LogData])
}
class FirstViewController: NSViewController {
var delegate:FirstViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
AppData.logs.append(newLogData)
self. delegate?.ViewControllerDelegate(appData: AppData.logs)
}
}
class SecondViewController: NSViewController,FirstViewControllerDelegate {
var firstViewController:FirstViewController = FirstViewController()
override func viewDidLoad() {
self.firstViewController.delegate = self
}
func ViewControllerDelegate(appData:[LogData]){
//Do Update the UI
}
}
In the code below, which (I hope) includes all that's relevant to my question, a mouseEntered/-Exited event in ChangerView is supposed to change the display in ChangingView. (ChangerView and ChangingView are displayed side-by-side and share a view controller.) As an OOP newbie, though, I'm seriously missing something about how to set up delegation between these views. Here's ChangerView (in which DoThis?.show = nil, despite that I thought I was setting it to true or false):
import Cocoa
protocol DoThis { var show: Bool { get set } }
class ChangerView: NSView {
var changeDelegate: DoThis?
// Set up for mouseEntered/-Exited
override func mouseEntered(theEvent: NSEvent) { DoThis?.show = true }
override func mouseExited(theEvent: NSEvent) { DoThis?.show = false }
}
And here's changing view:
import Cocoa
class ChangingView: NSView, DoThis {
var show: Bool = false { didSet { needsDisplay = true } }
// Draw into the view
override func drawRect(dirtyRect: NSRect) {
switch show {
case true: // Display setup contingent on show = true
case false: // Display setup contingent on show = false
}
// Draw contingent display
}
}
As I understand things, views should do their own basic display work, and view controllers should handle model-related and higher-level display changes. For that reason, and to keep things simple, I want ChangerView and ChangingView to communicate directly. Unfortunately, I couldn't find any explanations about delegation close enough to this situation—at least not that I could understand.
What am I missing (besides a properly functioning brain)?
Thanks!
It looks like there are two issues.
In your ChangerView class, you should be using the delegate to set the show variable, like this:
import Cocoa
protocol DoThis { var show: Bool { get set } }
class ChangerView: NSView {
var changeDelegate: DoThis?
// Set up for mouseEntered/-Exited
override func mouseEntered(theEvent: NSEvent) { changeDelegate?.show = true }
override func mouseExited(theEvent: NSEvent) { changeDelegate?.show = false }
}
You may want to make the delegate variable weak to prevent reference cycles
The other issue is you've forgot the step where you assign the delegate. I (and I think everyone else) forget this often. Once you get used to setting up delegates you'll remember to check for it if things don't work at first.
So at some point you need to set the changeDelegate var to an instance of the ChangingView class (this is often done in the viewDidLoad() function.
It will look something like this:
class SomeViewController: UIViewController {
#IBOutlet weak var SomeChangerView: ChangerView!
#IBOutlet weak var SomeChangingView: ChangingView!
override func viewDidLoad() {
super.viewDidLoad()
SomeChangerView.changerDelegate = SomeChangingView
}
I want to implement a didSet over a "sub-attribute" of a variable.
Example:
#IBOutlet weak var myLabel: UILabel!
var myLabel.hidden { didSet{ "DO SOMETHING" } }
I want to hide/show some other views when myLabel.hidden attribute change.
How can I do it?
You can make a property like this
var hideLabel: Bool = false {
didSet {
myLabel.isHidden = hideLabel
//SHOW OR HIDE OTHER VIEWS
}
}
By doing this you don't have to use KVO at the same time you can add more controls to hide to show at didSet context.
I Believe this is a simpler way to do such a thing.
The standard process is to use KVO. Add observer when the view is loaded:
override func viewDidLoad() {
super.viewDidLoad()
label.addObserver(self, forKeyPath: "hidden", options: .New | .Old, context: nil)
}
When the view controller is deallocated, make sure to remove the observer.
deinit {
label.removeObserver(self, forKeyPath: "hidden")
}
And do whatever you want inside the observeValueForKeyPath method:
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
NSLog("\(change)")
// do whatever you want here
}
Property observers can only be added to a class, not an instance. In order to do this you need to subclass UILabel and then override hidden's property observers.
EDIT: If you want to set custom observers on instances of CustomLabel, you can do this easily by adding block function variables to your CustomLabel that trigger on didSet or willSet
class CustomLabel: UILabel {
var onDidSetHidden: ((Bool) -> ())?
var onWillSetHidden: ((Bool) -> ())?
override var hidden: Bool {
didSet {
if let block = onDidSetHidden {
block(self.hidden)
}
}
willSet (willBeHidden) {
if let block = onWillSetHidden {
block(willBeHidden)
}
}
}
}
var custom = CustomLabel()
custom.onDidSetHidden = { (isHidden) in
if isHidden {
println("IS HIDDEN")
} else {
println("IS NOT HIDDEN")
}
}
custom.hidden = true //prints 'IS HIDDEN'