Search code examples
objective-cruntime

Does a property setter send messages in Objective-C?


Sending "messages" in Objective-C is a principal runtime function, which gets call when we compile our source code (though objc_msgSend).

If I understand correctly "message sending" is for instance variables. Since a properties without a weak or strong pointer are not initialized in the Heap, calling a setter's property won't "send a message", it will just call the "function" created automatically by the @property i.e. -(void)setNumber:(int)number , which happens in the Stack right?


Solution

  • Since a properties without a weak or strong pointer are not initialized in the Heap, calling a setter's property won't "send a message"

    It will send a message. The setNumber: method in your example is part of the object that owns the int - that is the object to which the message is sent, not the int, which cannot be a target of a message at all.

    @interface Demo : NSObject
    @property (nonatomic, readwrite) number;
    @end
    
    Demo *demo = [[Demo alloc] init]; // Creates the object
    // The following two lines are identical - they both send setNumber to demo
    demo.number = 123;
    [demo setNumber:123];
    

    It is also incorrect to say that primitives are not initialized in the heap: being part of their "host" objects, they are always allocated from the dynamic memory. The fact that they do not point to other heap memory in the same way that id properties do does not change the place where the properties themselves are allocated.