I have two subclasses, one that has a lot of customization, we'll call it Foo, and another sub class that only needs 1 method overridden, and doesn't need any additional variables, we'll call it Bar.
Bar will be one of the variables of Foo, so to keep from having 2 more files to work with (.m and .h for Bar) I would like to interface and implement Bar in Foo's .h and .m files.
My best effort gives me several compiler errors.
The .h file looks like:
#import <UIKit/UIKit.h>
@interface Foo : FooSuperClass {
Bar *barVariable;
}
@property (nonatomic, retain) Bar *barVariable;
-(void) fooMethod;
@end
@interface Bar : BarSuperClass {
}
@end
The .m file looks like:
#import "Foo.h"
@implementation Foo
@synthesize barVariable;
-(void) fooMethod{
//do foo related things
}
@end
@implementation Bar
- (void)barSuperClassMethodIWantToOverride{
}
@end
I realize that this type of things would generally be frowned upon, but I feel it's appropriate in my situation. The first error I get is "expected specifier-qualifier-list before Bar".
What have I done wrong, I'm pretty sure it's possible to have multiple declarations/definitions in a single file.
The compiler only considers types valid that it has seen before. As Nikolai mentioned, you could declare Bar
before Foo
.
However, that isn't always possible. For other situations, you can use @class
to forward declare the class.
I.e.
@class Bar;
@interface Foo : NSObject
{
Bar *bar;
}
@end
@class Bar;
tells the compiler that there exists a class named Bar and pointers to Bar should be considered valid.
In your header you've used Bar
before declaring it. Solution: Put Bar
's definition before Foo
's.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With