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??
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- CALayer - backgroundColor flipped?
- 求获取指定qq 资料的方法
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.
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.(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.
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
C# delegates are something like
NSInvocations
in Objective-C:however, an
NSInvocation
goes further: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.