JonnyB
JonnyB

Reputation: 355

Accessing Instance Variable in C Style Method

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 is throwing errors saying "XXX undeclared' where XXX is the instance variable name.

Here's an example of what I am explaining:

   @interface FontManager : NSObject {      
                CGFontRef fontRef;
   }

   static int CstyleFunction() {
        NSUInteger emSize = CGFontGetUnitsPerEm(fontRef);
   }

I want to verify that I cannot use "fontRef" from withing "CstyleFunction".

Any insight would be greatly appreciated.

Upvotes: 4

Views: 1112

Answers (3)

skue
skue

Reputation: 2077

@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.

Upvotes: 1

Anomie
Anomie

Reputation: 94794

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.

Upvotes: 3

jlehr
jlehr

Reputation: 15597

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.

Upvotes: 1

Related Questions