开发者

Accessing dynamically typed member

开发者 https://www.devze.com 2023-01-05 07:06 出处:网络
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 开发者_如何学Pythonfor two model classes that are very

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 开发者_如何学Pythonfor 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.


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]]) {
   ...
0

精彩评论

暂无评论...
验证码 换一张
取 消