Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

c# - Delegates in objective c

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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...