Need to cast in Objective C to use dot notation?
This is in the context of using Three20 but probably relates more to something I'm not getting aout Objective C. I'm in a TTTableLinkedItemCell
and simply trying to assign a property called readAt
.
//_item.readAt = [[NSDate alloc] init];
"Request for member 'readAt' in something not a structure or union"
[_item setReadAt: [[NSDate alloc] init]];
Works as expected. Then...
((NotificationItem *)_item).readAt = [[NSDate alloc] init];
Also works. It seems that I need to cast to use dot notation开发者_开发百科, but Obj-C will happily pass along messages blindly? Is this the correct rule I'm taking away from this?
PS: _item
, per the Three20 API, is: TTTableLinkedItem * _item
.
The compiler needs to know the object's type in order to use dot notation to access a property — casting is only necessary if the object wasn't statically typed to begin with. Message sends are valid for any object, so as long as the variable has some object type, it will work.
So why does it need to know the static type for a property accessor? Because a property can designate any method to be the getter or the setter, not just the default pair of foo
and setFoo:
, so the compiler needs to know what property this is in order to generate the correct accessor calls.
This page deals with a related question, although it is about your making own classes. There it is mentioned that in order for the compiler to recognize the property of the superclass when using the subclass, the subclass's implementation file must import the superclass's header file.
It seems that TTTableLinkedItemCell does not do this, so you are stuck with either casting or using the normal message syntax. Neither is ideal, but it's kind of out of your control.
精彩评论