Delegates in objective c

2020-02-12 13:48发布

First I should tell you that ive little knowledge of Objective C or C#.So when one of my collegues asked me whether there is anything like delegates in Objective C,I wondered if such a concept existed in Objective-C.I guess the delegates we use in iphone programing are not the same.C# delegates are function pointers right? Such a facility would be nice to have while working with multiple views.Where can i find info??

2条回答
狗以群分
2楼-- · 2020-02-12 14:36

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];
}
查看更多
Ridiculous、
3楼-- · 2020-02-12 14:38

C# delegates are something like NSInvocations in Objective-C:

  • each knows the object that will be the target of the call
  • each knows the method that will be called

however, an NSInvocation goes further:

  • it knows the arguments to pass to the method
  • it can store the return value

You probably wouldn't use NSInvocation to implement a pattern like C# delegates (which are a form of Proxy pattern). Personally I'd choose to use an object that forwards messages it receives to the target object, using the standard message-forwarding features of the runtime.

查看更多
登录 后发表回答