Skip navigation.
 
mlRe: Accessing variables from C functions in a Objective-C class
FROM : Andy Lee
DATE : Thu Nov 28 16:02:01 2002

At 5:29 PM +0100 11/28/02, Stefan Johansson wrote:
>Basiacally I need:
>
>1. Somehow get access to variables declared inside the @interface
>block from within a C function.
>2. If the above is not possible in any way, then some sort of class
>global variable, but it must NOT be shared among mulitple instances.


I'm having trouble understanding the "not shared among multiple
instances" part.  If foo is declared in the @interface, it is
*visible* to all instances of the class.  Whether it is *shared*
depends on how you declare it.

(a) If foo is declared *inside* the curly brackets, it is an instance
variable and each instance has its own (non-shared) value for foo.
In this case, you need some way to tell your C function which
instance's foo it should refer to.  We can talk about this if this is
what you wanted.

(b) If foo is declared *outside* the curly brackets, it is a plain C
variable whose value is shared by all instances; in fact, its value
is global across your entire program.

In case (b), you probably want to declare foo "extern", which is a C
keyword.  Besides declaring it, you will need to *define* it
somewhere, presumably in your .m file.  You will also need to
understand the difference between "declaring" and "defining" a
variable in C, and what happens when you define the same variable in
two places.  (This explains the "weird" occurrences you saw of
variables in seemingly different places having the same value.)

One other possibility is:

(c) If foo is not declared in the @interface block but rather in the
.m file, it can be shared by all instances of *that class*, and you
can choose to prevent it from being shared by instances of other
classes.

With option (c), each class can have its own foo, and a C function in
that class's .m will only refer to that class's foo.  Methods for
that class will also refer only that class's foo.

Is this what you meant?  If so, you need the C keyword "static":


----- ClassOne.m -----
@implementation ClassOne

static int foo;  // <== NOTE "static"

void functionOne()
{
    NSLog(@"the foo for ClassOne is %d", foo);
}

- (void)methodOne
{
    NSLog(@"the foo for ClassOne is %d", foo);
}

...

@end
----- end ClassOne.m -----


----- ClassTwo.m -----
@implementation ClassTwo

static int foo;

(void)functionTwo()
{
    NSLog(@"the foo for ClassTwo is %d", foo);
}

- (void)methodTwo
{
    NSLog(@"the foo for ClassTwo is %d", foo);
}

...

@end
----- end ClassTwo.m -----


--Andy