开发者

class variable scope issue with objc / cocoa?

开发者 https://www.devze.com 2023-02-27 09:19 出处:网络
Compiling in XCode 3.1.3 using GCC 4, under Leopard 10.5.8, with 10.5 as my target... I have an interface, thus:

Compiling in XCode 3.1.3 using GCC 4, under Leopard 10.5.8, with 10.5 as my target...

I have an interface, thus:

@interface testThing : NSObject { classContaininghooHa *ttv; }
@end

And an implementation, thus:

@implementation: testThing

- (void) instanceMethodMine
{
    [ttv hooHa]; // works perfectly, compiles, links, hooHa is invoked.
}

//    void cFunctionMine()
//    {
//        [ttv hooHa]; // compiler: 'ttv' undeclared (first use in this function) "
//    }

void stupidCFunctionMine((testThing 开发者_开发问答*)whom) // whom is passed class 'self' when invoked
{
   [whom instanceMethodMine]; // compiles, links, works. :/
}

@end

Now, my understanding -- clearly flawed -- was that if you declared a variable, class ID or otherwise, it was private to the class, but within the class, is performed essentially as a global, stored in the allocated class instance for the duration of its existence.

That's how it acts for objc methods.

But in the c function above, also written within the class, the variable appears to be invisible. The doesn't make sense to me, but there it is.

Can someone explain to me what is going on?

While you're at it, how can I declare this as an instance variable so I can use the method within a c function declared within the class scope as shown above, as well as within methods?

Insight much appreciated.


It doesn't make any difference where you are declaring/defining your "normal" c functions. They are not part of the class, they are just plain old c functions. No connection to the class whatsoever. Passing the instance they work on is a workaround if you really don't want to make this function a true objective-c method.


interface methods have full access to it's member variables. And the C function is not part of the class and so it cannot access any class variables unless it takes an class instance as the argument.

void cFunctionMine()
{
    [ttv hooHa]; // compiler: 'ttv' undeclared (first use in this function) 
}

Clearly cFunctionMine is not part of the interface. So it does not what ttv is to send the message hooHa.

While you're at it, how can I declare this as an instance variable so I can use the method within a c function declared within the class scope as shown above, as well as within methods?

void cFunctionMine()
{
    // 1. Create an instance using alloc and init

    testThing *ttv = [ [testThing alloc] init ] ;
    [ttv hooHa] ; 

    // Now the above statement is valid. We have a valid instance to which 
    // message can be passed to.

    // .....

    [ ttv release ] ;
    // release the resources once you are done to prevent memory leaks.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消