Duck
Duck

Reputation: 35953

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

objectC.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> ???!!!

Upvotes: 0

Views: 982

Answers (3)

John Lemberger
John Lemberger

Reputation: 2699

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.

Upvotes: 1

SVD
SVD

Reputation: 4753

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.

Upvotes: 1

codelark
codelark

Reputation: 12334

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];

Upvotes: 1

Related Questions