假设我在 Foo 类中创建了一个名为 Bar 的对象。 Bar 的代表是 Foo,我想像这样从 Foo 访问一个变量 [self.delegate variable]
.毫不奇怪,这会起作用,但会发出警告说“未找到 - 变量方法”所以我的问题是,我如何声明我希望委托(delegate)访问这个变量而不重写 getter 和 setter?
例如,如果我想声明委托(delegate)方法,它看起来像这样:
@interface NSObject(Foo)
- (void)someMethod;
@end
我如何对变量做同样的事情?
最佳答案
标准模式是定义一个 protocol
代表遵守的。例如:
@protocol BarDelegate
- (void) someMethod;
- (id) variable;
@end
然后在
Bar.h
你声明你的代表像:@interface Bar : NSObject {
id<BarDelegate> delegate;
}
//alternately:
@property(nonatomic, retain) id<BarDelegate> delegate;
@end
在
Foo.h
您声明您遵守协议(protocol):@interface Foo : NSObject<BarDelegate> {
}
@end
然后编译器警告将消失。
关于iphone - 在非正式协议(protocol)中委托(delegate)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412244/