1

Because I'm sick of misspelling a selector name I figured I'd try to do some notification stuff with blocks instead of selectors.

I've put together some sample code that doesn't seem to work because I'm unable to access self

var currentString : String?

// Type alias the notificaitonBlock
typealias notificationBlock = (NSNotification?) -> ()

// in this case note is an NSNotification?
let strNotification : notificationBlock = { notification in
    if let msg = notification?.object as? String {
        self.currentString = msg
    }
}

Assuming this code worked I would register it with:

nc.addObserverForName(UIDeviceOrientationDidChangeNotification, 
    object: self, 
    queue: NSOperationQueue.currentQueue(), 
    usingBlock: strNotification)

Xcode is giving me the following error:

NotificationTests.swift:49:4: 'NotificationTests -> () -> NotificationTests' does not have a member named 'currentString'

which implies self isn't pointing to the class but the block or something?

Jeef
  • 26,861
  • 21
  • 78
  • 156
  • are you declaring the notificationblock as an instance variable? – herby Mar 26 '15 at 20:20
  • I assume that it is the same issue as in http://stackoverflow.com/questions/25582853/type-does-not-have-a-member, http://stackoverflow.com/questions/25855137/viewcontrol-type-does-not-have-a-member-named and http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other/25856755#25856755: The initialization of one property cannot depend on the value of another property in the same class. – Martin R Mar 26 '15 at 20:23

1 Answers1

0

You could either use this when using an instance variable for the block:

lazy var block: (NSNotification?) -> () = { notification in
    if let msg = notification?.object as? String {
        self.currentString = msg
    }
}

or inside a method call:

func registerObeserver() {
    NSNotificationCenter.defaultCenter().addObserverForName(UIDeviceOrientationDidChangeNotification, object: self, queue: NSOperationQueue.currentQueue(), { notification in
        if let msg = notification?.object as? String {
            self.currentString = msg
        }
    })
}

As Martin R mentioned in the comments this probably has to do with one property of a class depending on another during initialization

Unlike this in javascript, self is not changing inside a closure

herby
  • 389
  • 3
  • 8