I just started to learn iOS programming and I have a problem with inheritance. There are 2 files.
First file
Header
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
int x;
}
@end
Implementation:
#import "ViewController.h"
#import "NewClass.h"
@implementation ViewController
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
x = 999;
NewClass *myClass = [[[NewClass alloc] init] autorelease];
}
@end
Second file
Header:
#import "ViewController.h"
@interface NewClass : ViewController
@end
Implementation:
#import "NewClass.h"
@implementation NewClass
-(id)init {
self = [super init];
if (self != nil) {
NSLog(@"%i",x);
}
return self;
}
@end
In ViewController I set x to 999, and in NewClass I want to get it, but when I call NSLog(@"%i",x); it gives me 0.
Where did I make a mistake?
You have a timing problem.
The
initmethod gets called first (at all levels of the inheritance hierarchy, so in bothViewControllerandNewClass). This is when you print out your value ofx, when it is still zero.The
viewDidLoadmethod only gets called much later, generally at a point after a view controller’s view has been added to a superview. It’s functionality that’s specific to theUIViewControllerclass.To make your example work, put an
initmethod in yourViewControllerclass that looks like the one in yourNewClassclass, and set x there.Also, you don’t need to create a
NewClassinstance withinViewController. When you create aNewClassobject, it is automatically aViewControlleras well. In the same way that a dog is an animal automatically, and so is a cat. When you create a dog, you don’t want to create an animal as well!As sidyll says, you should probably do a bit more reading about how inheritance works, I’m afraid!