开发者

iPhone - Accessing a delegate's property

I have 3 classes A, B and C.

B is a subclass of A. A has a property named theView.

I create an object based on B (objectB). Inside objectB I created an objectC based on class C, where

obj开发者_StackOverflow社区ectC.delegate = (id)objectB; 
objectB.delegate = (id)objectA;

how do I access objectB's theView property from inside objectC without having to import objectB's header? I would like to use just the delegate properties to do that.

If I try from C, for example:

CGRect bounds = [delegate.theView bounds];

I receive the error:

property theView not found on object of type id<classBdelegate> ???!!!


You could use key/value calls. They aren't type-checked at compile time, but will do the job without warnings. And if you get the wrong type of delegate at runtime the call will return null if it doesn't include the specified property (aka. key).

CGRect bounds = [[[delegate valueForKey:@"theView"] valueForKey:@"bounds"] CGRectValue];

All that said, the compile-time checking of SVD's answer would be better IMO.


If you don't use property notation, you don't need to import the header. The downside is you will have warnings about unknown selectors and a typo can lead to a runtime crash when the delegate object receives a selector it doesn't understand.

CGRect boundsRect = [[delegate theView] bounds];


To avoid a warning, create a protocol and cast your id-typed delegate as conforming to that protocol when its methods as codelark suggests. That is, in classC.m, before @implementation:

@protocol ViewHolder
-(UIView*) theView;
@end

and then when it is time to invoke:

CGRect boundsRect = [[((id<ViewHolder>)delegate) theView] bounds];

This way you won't get the warning normally, but will still get the warning if you mistype the name.

P.S. You can of course reuse that ViewHolder protocol definition elsewhere - just define it in a separate .h and include as needed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜