lucas_turci
lucas_turci

Reputation: 322

variable of type id

I have this code to add obstacles sprite nodes as childs to the concreteGround node:

-(void) addObstaclesToNode:(NSString *)pattern
{
    for(int index = 0; index<[self getPattern:pattern].arrayOfSprites.count; ++index)
    {
        id o = [[self getPattern:pattern].arrayOfSprites objectAtIndex:index];
        o.position = CGPointMake(o.position.x + windowW, o.position.y);
        [concreteGround addChild:[[self getPattern:pattern].arrayOfSprites objectAtIndex:index]];
    }
}

(getPattern is a method I created to return an object in an array) Anyway, I want the variable o to receive [[self getPattern:pattern].arrayOfSprites objectAtIndex:index], but that code can return various types of object. I used id to do so, but when I try to access a property of the object, Xcode tells me that "the property was not found on the object of type id". Am I doing something wrong? Thanks for the help...

Upvotes: 0

Views: 65

Answers (2)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

To your Q:

There is a big chaos in Objective-C related to declared properties. (Lattner was there?)

For the dot notation, even it does not say anything about the way the property and its accessors are implemented (synthesize or explicit) and declarared (@property or method declarations) the compiler does not accept any known property, but only properties of objects with known type.

You can do two things:

  1. Do not use dot notation for the access. (This is valid, if the method is declared anywhere.)

  2. Downcast the object.

BTW: Your code is not very Objective-Cish. You can use fast enumeration and indexed subscripting to make it better readable.

Upvotes: 3

i_am_jorf
i_am_jorf

Reputation: 54600

Yes, you need to make sure o is an instance of a class that supports that selector, or that it supports the selector.

if ([o isKindOfClass:[YCYourClass class]]) {
    YCYourClass *yourClass = o;
    yourClass.position = ...
}

Or:

if ([o respondsToSelector:@selector(setPosition:)]) {
    [o performSelector...
}

Although, now that I think about it, you may have just forgot to include the header where you declare the interface that has the position selector... that may work too.

Upvotes: 1

Related Questions