Accessing Instance Variable in C Style Method

后端 未结 3 1899
北恋
北恋 2021-01-19 13:07

Can someone confirm that you cannot access instance variables defined in an Objective C @implementation block from within C style functions of the same class? The compiler

3条回答
  •  醉梦人生
    2021-01-19 13:43

    @Anomie and @jlehr are correct, the C function has no concept of the FontManager object and its current state, it just happens to live in the same file.

    However, if FontManager is a singleton and you make fontRef a property (or create an accessor for it), then it would be possible to access the value within your C class:

    static int CstyleMethod() {
        FontManager *fm = [FontManager sharedManager];
        NSUInteger emSize = CGFontGetUnitsPerEm(fm.fontRef);
    }
    

    Bottom line, you can mix-and-match C and ObjC syntax within C functions & ObjC methods. But because C functions have no default reference to self (and the object's associated instance variables), you can only reference ObjC objects that are singletons, stored in a global variable, or passed in as parameters.

提交回复
热议问题