Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with inheritance in objective-C (iOS sdk)

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?

like image 433
KopBob Avatar asked Dec 12 '11 18:12

KopBob


2 Answers

You have a timing problem.

  1. The init method gets called first (at all levels of the inheritance hierarchy, so in both ViewController and NewClass). This is when you print out your value of x, when it is still zero.

  2. The viewDidLoad method 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 the UIViewController class.

To make your example work, put an init method in your ViewController class that looks like the one in your NewClass class, and set x there.

Also, you don't need to create a NewClass instance within ViewController. When you create a NewClass object, it is automatically a ViewController as 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!

like image 182
Joseph Humfrey Avatar answered Sep 25 '22 14:09

Joseph Humfrey


You need to review you OOP concepts. Object-Oriented Programming with Objective-C is a must.

Your class NewClass indeed inherits the x variable, but not it's value. When you create an instance of it, you're creating a shiny new instance whose values have nothing to do with the parent class.

Another point of view to help you is that x was set in a object of ViewController class. The NewClass inherits from ViewController class, not from an arbitrary instance (object, where you set x).

like image 25
sidyll Avatar answered Sep 22 '22 14:09

sidyll