#selector(Aclass.method)和#selector(self.method)之间的区别

时间:2016-04-07 20:18:08

标签: ios swift selector

有什么区别:

#selector(Aclass.someMethod)#selector(self.someMethod)

someMethod是一个实例函数,我在AClass内调用如下:

NSNotificationCenter.defaultCenter().addObserver(self, 
  selector: #selector(self.someMethod), // #selector(Aclass.method)
  name: "REMoveOrderViewRefresh", 
  object: nil
)

1 个答案:

答案 0 :(得分:4)

如果您引用自己班级的选择器,则应该没有区别,因为self指向Aclass

如果要引用其他类的选择器,则必须显式调用Aclass.someMethod,因为选择器不在self上,而是在另一个对象上。

class MyClass: NSObject {
    func someFunc() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.someOtherFunc(_:)), name: "someEvent", object: nil)
    }

    func someOtherFunc(notification: AnyObject) {
        //
    }
}

class OtherClass: NSObject {

    func anotherFunc() {
        let myInstance = MyClass()

        NSNotificationCenter.defaultCenter().addObserver(myInstance, selector: #selector(MyClass.someOtherFunc(_:)), name: "someEvent", object: nil)
    }
}