开发者

Custom Delegate Example in Objective-c

I understand using delegates in associated with other objects (i.e. UITextField etc.) But I am trying to find a simple example of setting up / using a custom delegate independently. Any help / pointers would be much appreciated.

My understanding so far is:

#import <Foundation/Foundation.h>

@class TheBox;

@protocol TheBoxDelegate <NSObject>
-(void)theBoxDelegateWillDoSomething:(TheBox *)theBox;
@end

@interface TheBox : NSObject {
    id <TheBoxDelegate> delegate;
}
@property(assign) id <TheBoxDelegate> delegate;
@end

.

#import "TheBox.h"

@implementation TheBox
@synthesize delegate;

@end

// Some other class will conform to <TheBoxDelegate> and 
// implement the method -(void)theBoxDelegateWillDoSomething:

The problem I am having within a simple basic app is where to i开发者_开发知识库nstantiate this, how to manage it memory wise and how to call it / get the delegate to give some simple feedback. One of the initial concepts that was tripping me up was that the method header defined in the protocol is implemented on the object conforming to the protocol.

Gary.


Delegation is just a design pattern, there is very little ceremony involved. Generally if you are trying to delegate a method you check to see if the delegate object implements the method in question (responds to the selector) and if so you pass the invocation on to that object.

Here is a good starting point in Appel's Docs on the subject.

http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜