Accessing Instance Variable in C Style Method

后端 未结 3 1900
北恋
北恋 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.

    0 讨论(0)
  • 2021-01-19 13:45

    A "C style method" doesn't really deserve the name "method", I'd call it a "function" instead as in C.

    A C function has no self, so it cannot implicitly access ivars as a method can. If you pass an instance to the C function as a parameter, you can access ivars in the same manner you would access a field in a struct pointer.

    0 讨论(0)
  • 2021-01-19 13:55

    That's correct. You seem to be mixing up methods and functions though. Methods exist only in Objective-C. What you're referring to as a 'C style method' is really just a C function.

    C is not an object-oriented programming language. Since there's no such thing as an object in C, there's also no such thing as an instance variable in C, so the fontRef instance variable would not be visible in the function you posted, nor for that matter in any other C function in your program.

    0 讨论(0)
提交回复
热议问题