Delegates in Objective-C are merely a concept, not some kind of implementation artifact (like in C#). A delegate in Objective-C (better: Cocoa) is basically an object, which is notified by whoever uses it as its "delegate" of certain events occuring. Delegates may also be asked to perform certain tasks on behalf of the host object. The interface a delegate is required to implement is often formalized by a protocol.
@protocol ActionDelegate
- (void) actionDidStart: (id) aSender;
- (void) actionDidEnd: (id) aSender;
@end
@interface Action: NSObject {
id<ActionDelegate> delegate;
}
@property (nonatomic,assign) id<ActionDelegate> delegate;
@end
Delegates in C#, on the other hand, are an implementation artifact. There is a dedicated delegate
keyword to declare delegate types and to create actual delegate instances.
class Action {
delegate void ActionDidStartDelegate(Action sender);
delegate void ActionDidEndDelegate(Action sender);
...
}
(my C# is a bit rusty, so the syntax may be off here, sorry; and in real life, one would probably use events in situations like the above rather than raw delegates). Basically, a C# delegate is akin to a Python method object.
You might be able to use the new code block feature of Objective-C to emulate delegates. Not having used this feature (yet), I cannot comment on this. Another way to get something like that would be to use plain function pointers.
typedef void (*callback_function)();
- (void) doSomethingWithCallback: (callback_function) func {
...
func();
}
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
- (void) doSomethingWhenDonePerform: (SEL)aSelector onObject: (id) aReceiver {
...
[aReceiver perform: aSelector];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…