Search code examples
objective-cobjectcastingnsnotifications

Is casting ever required for the object on an NSNotification?


When I receive an NSNotification do I ever need to cast notification.object? Suppose I know notification.object will be an instance of MyClass and I do the following:

MyClass *myClass = notification.object;

Is any casting necessary here? How is the above assignment different from:

MyClass *myClass = (MyClass *)notification.object;

Solution

  • No, it is entirely unneccessary and does not change anything about the behavior of your program. Casting only happens at compile time, and in the case of pointers, is just used to assure the compiler that you know what type the object is.

    The compiler may complain about an assignment if you are, for example, setting a variable of type Subclass to the result of a method that returns type Superclass, where you know that the actual object you are going to get back is of type Subclass. In that case, you would cast to the subclass. E.g.,

    MyViewController * vc = (MyViewController *)[someWindow rootViewController];
    

    The type of notification.object is id, a generic object pointer, and the compiler is perfectly happy to assign such a pointer to any other type of pointer.