Tum
Tum

Reputation: 7585

Can't access properties of instance in NSArray

I'm trying to get and set properties from an instance of a class from its parent. It works if I simply create the object and get or set them immediately, but if I put the instances in an NSArray it says it's not found:

Property 'pos' not found on object of type 'id'

I have this viewcontroller called Gameplay.m (UIViewController) where I create instances of class Wall (UIView) in the ViewDidLoad method:

walls = [[NSMutableArray alloc] initWithCapacity:10];

for(int i = 0; i < 10; i++) {
    Wall *wall = [[Wall alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
    wall.opaque = NO;
    wall.backgroundColor = [UIColor clearColor];
    [wall setFrame:CGRectMake(levelpos.x + 200 * i, levelpos.y, 200, 200)];
    wall.pos = CGPointMake(levelpos.x + 200 * i, levelpos.y); //setting instance attribute works!
    [self.view addSubview:wall];
    wall.userInteractionEnabled = NO;
    [walls addObject:wall];
}

walls[0].pos = CGPointMake(0, 0); //Doesn't work!

The property 'pos' of class Wall is declared like this in Wall.h:

@interface Wall : UIView

@property (nonatomic, assign) CGPoint pos;

I have very little experience in both Objective C and OOP, there must be something I'm missing.

Upvotes: 2

Views: 290

Answers (3)

CodaFi
CodaFi

Reputation: 43330

Array Subscripting returns objects of type id, which are far as the compiler knows is a pointer to a struct. id has only one member (isa), and declares no properties, thus trying to use it as an object is a compile time error. Just cast the result of the Subscripting to the type of the object you want to message.

((Wall *)walls[0]).pos = CGPointMake(0, 0); //Does work

Upvotes: 2

iCoder
iCoder

Reputation: 1645

make sure u have imported

 #import "Wall.h"

and change

walls[0].pos = CGPointMake(0, 0);

to

((Wall *)walls[0]).pos = CGPointMake(0, 0);

Upvotes: 1

zbMax
zbMax

Reputation: 2818

when you write walls[0], you access to an object of your array but you "don't know" what it is. So cast it with ((Wall*)walls[0]).pos

Upvotes: 1

Related Questions