您的位置:首页 > 移动开发 > Objective-C

How to use custom delegates in Objective-C

2011-11-22 10:18 387 查看
You will want to declare a delegate protocol for your class. An example of a delegate protocol and interface for class
Foo
might
look like this:
view plain@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

[/code]

Don't forget to synthesize your properties in the
@implementation
.

What this code did was declare a protocol called FooDelegate; a class that conforms to this protocol would be declared like
@interface
SomeClass : SuperClass <FooDelegate> {}
. Because this class conforms to the protocol
FooDelegate
,
it now gets to implement the methods under
FooDelegate
(to
require that these be implemented, use
@required
instead
of
@optional
).
The last step is for a
Foo
object
to be instantiated in the class that conforms to
FooDelegate
,
and for this
Foo
object
to have its delegate property set:
view plainFoo *obj = [[Foo alloc] init];
[obj setDelegate:self];
[/code]

Now, your class is prepared to receive messages from
Foo
objects
that have their delegates set correctly.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: