我需要了解Objective-C中委托方法的用法.谁能指出我正确的来源?
您需要为您的类声明委托协议.类的委托协议和接口的示例Foo
可能如下所示:
@class Foo; @protocol FooDelegate@optional - (BOOL)foo:(Foo *)foo willDoSomethingAnimated:(BOOL)flag; - (void)foo:(Foo *)foo didDoSomethingAnimated:(BOOL)flag; @end @interface Foo : NSObject { NSString *bar; id delegate; } @property (nonatomic, retain) NSString *bar; @property (nonatomic, assign) id delegate; - (void)someAction; @end
别忘了合成你的房产@implementation
.
这段代码的作用是声明一个名为FooDelegate的协议; 符合此协议的类将被声明为@interface SomeClass : SuperClass
.因为这个类符合协议FooDelegate
,所以它现在可以实现下面的方法FooDelegate
(要求实现这些方法,@required
而不是使用它们@optional
).最后一步是Foo
在符合的类中对象进行实例化FooDelegate
,并为此Foo
对象设置其delegate属性:
Foo *obj = [[Foo alloc] init]; [obj setDelegate:self];
现在,您的类已准备好接收来自Foo
正确设置其委托的对象的消息.
代理对于手动控制应用程序中视图控制器数组内的传输非常有用.使用代理,您可以很好地管理控制流程.
这是自己代表的一个小例子....
创建协议类....(仅限.h)
SampleDelegate.h
#import @protocol SampleDelegate @optional #pragma Home Delegate -(NSString *)getViewName; @end
在要为其他类委托的类中导入上面的协议类.在我的前任.我使用AppDelegate来创建HomeViewController的Object的委托.
还在Delegate Reference <>中添加了DelegateName
ownDelegateAppDelegate.h
#import "SampleDelegate.h" @interface ownDelegateAppDelegate : NSObject{ }
ownDelegateAppDelegate.m
//setDelegate of the HomeViewController's object as [homeViewControllerObject setDelegate:self]; //add this delegate method definition -(NSString *)getViewName { return @"Delegate Called"; }
HomeViewController.h
#import #import "SampleDelegate.h" @interface HomeViewController : UIViewController { iddelegate; } @property(readwrite , assign) id delegate; @end
HomeViewController.h
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; UILabel *lblTitle = [[UILabel alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; lblTitle.text = [delegate getViewName]; lblTitle.textAlignment = UITextAlignmentCenter; [self.view addSubview:lblTitle]; }