Accessing an instance variable in a C style method

Can someone confirm that you cannot access the instance variables defined in the Objective-C @implementation block from C-style methods of the same class? The compiler throws errors saying "XXX undeclared", where XXX is the name of the instance variable.

Here is an example of what I explain:

@interface FontManager : NSObject { CGFontRef fontRef; } static int CstyleMethod() { NSUInteger emSize = CGFontGetUnitsPerEm(fontRef); } 

I want to verify that I cannot use the "fontRef" from "CstyleMethod".

Any understanding would be greatly appreciated.

+4
source share
3 answers

The style method “C” does not really deserve the name “method”; I would call it a “function”, not like C.

The C function does not have self , so it cannot implicitly access ivars as a method. If you pass an instance of function C as a parameter, you can access ivars in the same way as you access a field in a structure pointer.

+2
source

It is right. You seem to be mixing methods and functions. Methods exist only in Objective-C. What you call the “C style method” is actually just a function of C.

C is not an object-oriented programming language. Since there is no such thing as an object in C, there is also no such thing as an instance variable in C, so the fontRef instance variable fontRef not be visible in the function you sent, and in this case, no other C function in your program.

0
source

@Anomie and @jlehr are correct, the C function has no idea about the FontManager object and its current state, it just lives in one file.

However, if the FontManager is singleton, and you create the fontRef property (or create an accessor for it), then you can access the value in your C class:

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

On the bottom line, you can combine and map the syntax of C and ObjC inside C functions and ObjC methods. But since C functions do not have a default reference to self (and instance variables associated with the object), you can only reference ObjC objects that are single, stored in a global variable, or passed as parameters.

0
source

Source: https://habr.com/ru/post/1343275/


All Articles