1

Say I create an object in class Foo called Bar. Bar's delegate is Foo and I want to access a variable from Foo like this [self.delegate variable]. Not surprisingly, this will work but give a warning saying "No -variable method found" So my question is, how do I declare that I want this variable to be accessed by a delegate without rewriting the getters and setters?

For example, if I wanted to declare delegate methods, it would look something like this:

@interface NSObject(Foo)
- (void)someMethod;
@end

How do I do the same with variables?

Justin
  • 315
  • 2
  • 13

1 Answers1

3

The standard pattern is to define a protocol that the delegate conforms to. For example:

@protocol BarDelegate
- (void) someMethod;
- (id) variable;
@end

Then in Bar.h you declare your delegate like:

@interface Bar : NSObject {
    id<BarDelegate> delegate;
}

//alternately:
@property(nonatomic, retain) id<BarDelegate> delegate;
@end

And in Foo.h you declare that you conform to the protocol:

@interface Foo : NSObject<BarDelegate> {
}
@end

Then the compiler warnings will go away.

aroth
  • 54,026
  • 20
  • 135
  • 176
  • Can you do the same with an informal protocol though? – Justin Mar 23 '11 at 22:32
  • As long as the members you want access to are exposed via getter functions, you should be able to do `@interface NSObject(Foo) - (id)variable; @end`, though according to [this other answer](http://stackoverflow.com/questions/2010058/informal-protocol-in-objective-c) creating informal protocols by adding categories on NSObject has fallen out of favor. – aroth Mar 23 '11 at 22:52
  • The `@optional` keyword is only available in newer versions of OS X. If you want to support older versions, an informal protocol is still required. – ughoavgfhw Mar 24 '11 at 00:18