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

I just started learning iOS programming and I have a problem with inheritance. There are 2 files.

First file

Headline

#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

Title:

#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?

+5
source share
3 answers

You have a synchronization problem.

  • The method initis called first (at all levels of the inheritance hierarchy, therefore in ViewControllerand NewClass). This is when you print your value x, when it is still zero.

  • viewDidLoad , , , . , UIViewController.

, init ViewController, , NewClass, x.

, NewClass ViewController. NewClass, ViewController. , , . , !

, , , , .

+8

. - Objective-C .

NewClass x, . , , .

, , , x ViewController. NewClass ViewController , (, x).

+6

, -viewDidLoad , -init. ​​ -init.

0
source

All Articles