user1467267
user1467267

Reputation:

Objective-C Class init parameters

I'm currently starting up with some Objective-C again. The problem I have is passing variables to the native init method of a class instance.

I have this custom init in my @interface:

-(id)init
{
    if(self = [super init]) {
        level = 1;
        NSLog(@"Debug response");
    }

    return ([NSObject init]); // return self;
}

And here's my App's main class:

#import "AppDelegate.h"
#import "PlayableCharacter.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    NSArray *params = [NSArray arrayWithObjects: @"Elf", nil];

    PlayableCharacter *allendar = [[PlayableCharacter alloc] init:params];
}

@end

Can someone explain what I'm doing wrong? I thought an NSArray object would fit the profile of an "id" C-object. Is giving init parameters illegal or must it be done in another way?

The Error states: "No visible @interface for 'PlayableCharacter' declares the selector 'init:'"

Upvotes: 3

Views: 12569

Answers (2)

colincameron
colincameron

Reputation: 2704

If you want to init with parameters then create an init method like this:

-(id)initWithParams:(NSArray *)params
{
    if(self = [super init]) {
        level = 1;
        NSLog(@"Debug response");

        // Do something with params
    }

    return self;
}

Also, you should just return self, not [NSObject init]

Upvotes: 4

Lily Ballard
Lily Ballard

Reputation: 185801

Your -init method doesn't have any params. It's equivalent to the following C:

void *init();

void *foo = init(bar); // error

If you want to call it as -init:, then you would declare it as

- (id)init:(NSArray *)params;

However, this is very much a non-standard naming. If you really want an init method that takes a single NSArray, then maybe name it something like

- (id)initWithArray:(NSArray *)array;

But from your sample code I'm guessing you don't really need an array, you just need one parameter. So instead you'd use

- (id)initWithCharacterClass:(NSString *)className;

and then call it as

PlayableCharacter *allendar = [[PlayableCharacter alloc] initWithCharacterClass:@"Elf"];

Upvotes: 10

Related Questions