iDevGames Forums
Objective-C Class allocation crash - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: Objective-C Class allocation crash (/thread-1922.html)



Objective-C Class allocation crash - MrMegabytes - Jan 12, 2009 06:11 AM

Hey guys, this is a real noobie question so please bare with me. I'm 100% new to Mac, only had this macbook for a week. I want to get into IPhone dev and here I am. I've been writing code for c/c++ windows applications for some time now so i'm not a coding noob, just obj-c Grin

Anyway, here is my question.
I'm trying to allocate memory for a near empty class. But its crashing on the alloc function... here we go..

Sprite.h file
Code:
@interface Sprite
{
    @private
        bool m_init;

}

- (void)draw;

@end


Sprite.m
Code:
#import "Sprite.h"

@implementation Sprite
- (void)init
{
    m_init = TRUE;
}

- (void)draw
{
}

@end

ELGLView.m offending code
Code:
        if( !m_init )
        {
            m_sprite = [[Sprite alloc] init];
            m_init = TRUE;
        }

I have m_sprite decleared in the ELGView.h file. When I compile i get a waring saying:

Warning: 'Sprite' may not respond to '+alloc'

I'm not sure what that warning means either, but i'm sure it has something to do with my crash. When i rush i through the Iphone simulator it crashes and asks if i want to reload.

When i step through the code it comes up to the
Code:
m_sprite = [[Sprite alloc] init];
line and the callstack says its finished in __forwarding__
Looking at tutorials it appears to be correct, but there might be something very simple that i've forgotten somewhere. Any help would be greatly appreciated.


Objective-C Class allocation crash - ThemsAllTook - Jan 12, 2009 08:16 AM

+alloc is an NSObject method. You'll want to change your Sprite interface to subclass NSObject, like so:

Code:
#import <Cocoa/Cocoa.h>

@interface Sprite : NSObject

In most cases, you'll want all of your objects to subclass NSObject (or a subclass thereof).


Objective-C Class allocation crash - DoG - Jan 12, 2009 02:28 PM

And -init must return self. Please read the docs, again if you have done so already.