-->

Strange error regarding instance variables & super

2019-04-26 20:45发布

问题:

I've got some code where my classes inherit from a superclass, and everything has been working fine till now. I'm getting an error whenever I try to use any of the superclass variables, saying that they are undeclared (first use in this function). It's only happening in one of my subclasses, & it looks exactly the same as the others. I'm wondering if there's anything obvious which I should know about (being quite new to Objective-C). The basic code is like -

@interface mySuperClass : UIViewController {

BOOL myVar;

}

Then -

@interface mySubClass : mySuperClass {

}

@implementation mySubClass {

-(void)someMethod {

    myVar = YES; // error here

}

@end

Any help much appreciated - if you need more info, let me know! Thanks.

回答1:

I just got over a very similar strange error where I could no longer access properties in my superclass, and xcode was givine me compiler errors saying "(*) undeclared (first use in this function)". However I had not any problems in the past...

The problem was that I had introduced typos at the top of my .m file and the xcode compiler output was misleading me. Specifically I had @synthesize statements where the properties were misspelled, either in the synthesize statement or in the corresponding variable in the headerfile.

If you have @synthesize statements or other declarations, examine them with a fine toothed comb (i.e. which lines have you introduce most recently?), or even comment out a block of them to see if you can compile again and narrow down the culprit.

Again the compiler errors were very misleading, so it really was tough to debug. Although like 99.9% of the time the error was my own. :)



回答2:

I can't see anything wrong with the code you've pasted. My first guess would be that you're not importing the mySuperClass .h file properly. Ie you're missing

#import "mySuperClass.h"    //or #include

In mySubClass.h, or mySubClass.m



回答3:

I ran into the same problem and after wasting hours I finally solved it in my project:

I refactored my source and removed a member but forgot to remove the @property definition in .h file. This leads to errors at every place when I am using super members. BTW: Methods from super are fine.

So check your property defs. Thanks to Screwtape in post 8 for his solution :-)

EDIT: Oops, Kris' answer is pretty similar except from typos vs. removal.



回答4:

I am having the same issue for weeks

"Variable Undeclared" error when compiling to iOS Device, but not for Simulator

One solution I found is to simply change the compiler from the default LLVM GCC 4.2 to LLVM Compiler 2.0 (or to `Apple LLVM Compiler 2.1). It seems to be a bug in the compiler, but it is just a guess.

Changing it is a quick fix for your problem if there is no need for you to use the GCC compiler at all.