关于objective-c的代理

 

 

最近在iphone平台做一个游戏,在实现横竖切换时,出现如下情况:

一个ViewController控制着AView和BView。
现在要实现:AView中点击切换到BView,BView中点击又切换回AView中,并把

Bview删除或隐藏。
由于对模式不是很清楚,所以没想到用什么模式处理,如果有什么好的模式可以

解决上述问题,希望大侠们指教哇。
最后使用的方法是objective-c的代理。

1.在BView.h中定义一个代理:
id delegate; // A delegate that wants to act on events in this view
2.定义代理方法,这里使用到的是objective-c 的协议
@interface NSObject ( BViewDelegate)
-(void)delegateMethod;
@end
注:以上写的协议为非正式的,所以,不用被设置代理者,不实现这个代理方法

也是可以的。
3.在点击中实现代码中,调用代理者实现的代理方法。在BView.m中添加如何类似

代码:
//设置了代理者,且代理者实现了delegateMethod
if(delegate && [delegate respondsToSelector:@selector(delegateMethod)])

 
       delegate delegateMethod];

4.在AViem.m中设置BView的代理,并实现delegateMethod方法即可:
类似初始化中添加:[aView setDelegate:self];
-(void)delegateMethod{
      //control bView code here
      ...
}

 

另外,关于正式协议:
@protocol protocolName
@optional -(void)delegateMethodA
@required -(void)delegateMethodB
// other methods
...
@end
正式协议类似于java的借口或抽象类。@optional 的方法,可实现也可不实现,

但@required 的方法必需实现。默认为@required。
正式协议要求在代理类中声明采纳此代理,如:
@interface ClassName: NSObject <ProtocolName>
//...
@end
另外,在调用特殊代理方法前,需要通过conformsToProtocol函数来判断代理对

象是否遵守定义的协议,如:
if([mydelegate conformsToProtocol:@protocol(protocolName)])
{
      [mydelegate delegateMethod];
}

或者使用respondsToSelector:@selector来判断代理对象是否实现相应的方法。

 


 参考资料:
http://en.wikipedia.org/wiki/Delegation_pattern
http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c
http://icocoa.cn/ocsection/ocpractice/59-oc-protocol

 

posted @ 2009-07-01 17:03  simalone  阅读(1844)  评论(0编辑  收藏  举报