Custom Delegate Example in Objective-c

匿名 (未验证) 提交于 2019-12-03 09:18:39

问题:

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 instantiate 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.

回答1:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!