Matt N.
Matt N.

Reputation: 1239

Inheritance in Objective C

I have a main game class which renders the game using Open GL. Now I thought I could inherit from this class and then just call [super init] in its init method to get a copy of it. The plan was to make some modifications in the copy but as it seems this doesn't work.

The following is the header file of my class:

#import "GameView.h"


@interface CloneView : GameView {

}

-(id)initWithFrame:(CGRect)frame;

@end

And this is the Clone view class:

@implementation CloneView

-(id)initWithFrame:(CGRect)frame{
    return [super initWithFrame:frame];
}

@end

If I set a break point in the init method in the GameView class it stops there. Thing is: my clone view doesn't get rendered, the screen stays black. What am I missing? Thanks for your help!

Edit Just for the record: I tried without implementing initFrame and got the same result. (as expected as the initFrame as above isn't doing anything apart from calling super)

Edit 2 I'm adding my clone to another view so I'm creating two Eagle contexts. Could that be the reason why it doesn't work?

Upvotes: 2

Views: 130

Answers (4)

Matt N.
Matt N.

Reputation: 1239

I finally located the problem:

I needed to write a second init method. The problem was that the following code was being executed twice:

CAEAGLLayer *eaglLayer = (CAEAGLLayer *)[super layer];
[eaglLayer setOpaque:YES];
m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
if (!m_context || ![EAGLContext setCurrentContext:m_context]) {
    printf("FAIL \n");
    [self release];
    return nil;
}
[Textures loadTexture];
    if ([self createFramebuffer]) {
    [self draw];
}

This code was in the initFrame method of the game class. I made a second init method that does not execute this code. Instead, this code is executed in the parent view class of the clone. Now it works, YAY!! Thanks for trying to help me!

Upvotes: 0

Vidyanand
Vidyanand

Reputation: 967

This is from the apple docs

You should assign self to the value returned by the initializer because the initializer could return an object different from the one returned by the original receiver.

So Try doing this

-(id)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame] ) {
         //Do whatever you need to do here. 
    }
    return self;
 }

This should fix your issue if you need to do something in your init method. Otherwise you can skip the init method altogether.

Upvotes: 1

Dinakar
Dinakar

Reputation: 1208

try doing this it may work..

return(self=[super initWithFrame:frame]) which ensures the super class method is copied properly to the current method

TNQ

Upvotes: 0

Mihai Fratu
Mihai Fratu

Reputation: 7663

If you are not adding anything in the init function of CloneView than you don't even have to rewrite it. You can just have your class inherit from GameView and it automatically copies it's init function.

Upvotes: 1

Related Questions