Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C multiple class definitions in one .h and .m

Tags:

objective-c

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.

like image 888
SooDesuNe Avatar asked Oct 04 '09 15:10

SooDesuNe


2 Answers

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.

like image 84
bbum Avatar answered Sep 20 '22 14:09

bbum


In your header you've used Bar before declaring it. Solution: Put Bar's definition before Foo's.

like image 24
Nikolai Ruhe Avatar answered Sep 20 '22 14:09

Nikolai Ruhe