Search code examples
ioscalayerobjective-c-category

why can CALayer's category declare a property without implementation and use it directly?


As far as i know, you should not define an instance variable in a category, and if you declare a property, that only means you delclare the "setter & getter" methods.

@interface CALayer (XQ)
    @property NSString *demoVar;
    - (void)demoFunc;
@end
@implementation CALayer (XQ)
    - (void)demoFunc {
        self.demoVar = @"cuteeeee";
        NSLog(@"%@", self.demoVar);// when i call this method, it should crash, but the output is normal, why?
    }
@end

Sorry for my poor English and phrase, thanks.


Solution

  • A comment in CALayer.h states:

    /** Property methods. **/
    
    /* CALayer implements the standard NSKeyValueCoding protocol for all
     * Objective C properties defined by the class and its subclasses. It
     * dynamically implements missing accessor methods for properties
     * declared by subclasses.
    

    Apparently CALayer treats properties declared in categories the same as it treats properties declared in subclasses, so it is dynamically implementing the accessor methods for you.