mardi 28 juin 2016

In a Swift extension, get the actual calling object?

Say we are in an instance of SomeClass, consider this simple call

NSNotificationCenter.defaultCenter().addObserver(
 self,
 selector: #selector(SomeClass.fixer(_:)),
 name:"FixerNote",
 object:nil)

Say we decide to make an extension to save typing, that will look like this ...

"FixerNote".does( #selector(SomeClass.fixer(_:)) )

Here's the extension...

public extension String
    {
    func does(s:Selector)
        {
        NSNotificationCenter.defaultCenter().addObserver
           .. here, you need the actual SomeClass that called us .. ,
            selector: s,
            name:self,
            object:nil)
        }
}

How to know which object called the extension??

(NB, I realize you could pass it in or use it as the base :) )

Can you do such a thing in Swift? Can you find out who called you?

A similar issue: in the example, could you find out what object a selector ("s" in the example) belongs to ??





Aucun commentaire:

Enregistrer un commentaire