Sre*_*lal 51 cocoa-touch delegates objective-c
我需要了解Objective-C中委托方法的用法.谁能指出我正确的来源?
Jon*_*ing 128
您需要为您的类声明委托协议.类的委托协议和接口的示例Foo可能如下所示:
@class Foo;
@protocol FooDelegate <NSObject>
@optional
- (BOOL)foo:(Foo *)foo willDoSomethingAnimated:(BOOL)flag;
- (void)foo:(Foo *)foo didDoSomethingAnimated:(BOOL)flag;
@end
@interface Foo : NSObject {
NSString *bar;
id <FooDelegate> delegate;
}
@property (nonatomic, retain) NSString *bar;
@property (nonatomic, assign) id <FooDelegate> delegate;
- (void)someAction;
@end
Run Code Online (Sandbox Code Playgroud)
别忘了合成你的房产@implementation.
这段代码的作用是声明一个名为FooDelegate的协议; 符合此协议的类将被声明为@interface SomeClass : SuperClass <FooDelegate> {}.因为这个类符合协议FooDelegate,所以它现在可以实现下面的方法FooDelegate(要求实现这些方法,@required而不是使用它们@optional).最后一步是Foo在符合的类中对象进行实例化FooDelegate,并为此Foo对象设置其delegate属性:
Foo *obj = [[Foo alloc] init];
[obj setDelegate:self];
Run Code Online (Sandbox Code Playgroud)
现在,您的类已准备好接收来自Foo正确设置其委托的对象的消息.
代理对于手动控制应用程序中视图控制器数组内的传输非常有用.使用代理,您可以很好地管理控制流程.
这是自己代表的一个小例子....
SampleDelegate.h
#import
@protocol SampleDelegate
@optional
#pragma Home Delegate
-(NSString *)getViewName;
@end
Run Code Online (Sandbox Code Playgroud)
还在Delegate Reference <>中添加了DelegateName
ownDelegateAppDelegate.h
#import "SampleDelegate.h"
@interface ownDelegateAppDelegate : NSObject <UIApplicationDelegate, SampleDelegate>
{
}
Run Code Online (Sandbox Code Playgroud)
ownDelegateAppDelegate.m
//setDelegate of the HomeViewController's object as
[homeViewControllerObject setDelegate:self];
//add this delegate method definition
-(NSString *)getViewName
{
return @"Delegate Called";
}
Run Code Online (Sandbox Code Playgroud)
HomeViewController.h
#import
#import "SampleDelegate.h"
@interface HomeViewController : UIViewController
{
id<SampleDelegate>delegate;
}
@property(readwrite , assign) id<SampleDelegate>delegate;
@end
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61593 次 |
| 最近记录: |