views:

21

answers:

1

I have a dynamically typed member id currentEvent in my view controller class. The rationale is that the view controller is used to display data for two model classes that are very similar.

I have a setter:

-(void)setCurrentEvent:(id)e {
    [self.currentEvent release];
    Class eventClass = [e class];
    currentEvent = [[eventClass alloc] init];
    currentEvent = [e retain];
}

Now I want to access a member of the class:

    return [currentEvent.comments count];

But the compiler complains: request for member 'comments' in something not a structure or union.

I am afraid I have a fundamental misconception about dynamic typing, but I hope it's something much simpler.

A: 

Some problems with your setter: (1) don't call the getter (self.currentEvent) when releasing the ivar, (2) always retain the new obj before releasing the old obj, in case it is the same obj, ie:

-(void)setCurrentEvent:(id)e {
    [e retain];
    [currentEvent release];
    currentEvent = e;
}

That aside, I don't understand what your trying to do with dynamic typing.

This line will cause a compiler warning because you've told it that currentEvent is an id, which doesn't have a comments member, so it rightly complains:

return [currentEvent.comments count];

If somehow you know that the id currentEvent is actually an object of a particular class that has a comments you can cast the id to another type to avoid the warning:

return [(CommentEvent*)currentEvent.comments count];

But before you do that, how do you know? You could check to see if it is the right class:

if ([currentEvent isKindOfClass:[CommentEvent class]]) {
   ...
progrmr
Thanks for the corrections to the setter. I am at a point where I can accomplish most of the things I want and need to, but still feel sometimes that I lack some basic understanding of Objective-C concepts which causes me to get basics like this not quite right. On the dynamic typing -- I was trying to avoid writing almost the same code twice, but realized that I would be much better off going back to the two classes that are similar and rewrite them so that I can use the same class for the two types of objects.Thanks for the `isKindOfClass` suggestion too.
mvexel