开发者

Delegate variables in an informal protocol

Say开发者_StackOverflow中文版 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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜