user2577959
user2577959

Reputation: 295

Objective C - How to instantiate a class saved as a variable

I am new to Objective C and I'm getting confused by this concept.

The following method is supposed to create instances of the class that is passed as a parameter and edit the instance's variables.

- (void) createObject:(Class)objecttype atPoint: (CGPoint)position {

    if ([objecttype isSubclassOfClass:[GameObject class]]){

        id theobject = [[objecttype alloc] init];

        theobject.x = position.x; //error
        theobject.y = position.y; //error
    }
}

I get an error message where indicated above : Property 'x' not found on object of type '__strong id'

It seems like it should be simple, but I don't understand whats wrong.

Upvotes: 2

Views: 177

Answers (1)

bbum
bbum

Reputation: 162712

The dot notation will not call methods on objects of type id.

Change that allocation line to:

GameObject *theobject = (GameObject*)[[objecttype alloc] init];

Note that, because of the isSubclassOfClass: conditional, the above cast is precisely correct.

Upvotes: 6

Related Questions