How to perform Callbacks in Objective-C

Objective CCocoaCallback

Objective C Problem Overview

How to perform call back functions in Objective-C?

I would just like to see some completed examples and I should understand it.

Objective C Solutions

Solution 1 - Objective C

For completeness, since StackOverflow RSS just randomly resurrected the question for me, the other (newer) option is to use blocks:

@interface MyClass: NSObject
    void (^_completionHandler)(int someParameter);

- (void) doSomethingWithCompletionHandler:(void(^)(int))handler;

@implementation MyClass

- (void) doSomethingWithCompletionHandler:(void(^)(int))handler
    // NOTE: copying is very important if you'll call the callback asynchronously,
    // even with garbage collection!
    _completionHandler = [handler copy];
    // Do stuff, possibly asynchronously...
    int result = 5 + 3;
    // Call completion handler.
    // Clean up.
    [_completionHandler release];
    _completionHandler = nil;



MyClass *foo = [[MyClass alloc] init];
int x = 2;
[foo doSomethingWithCompletionHandler:^(int result){
    // Prints 10
    NSLog(@"%i", x + result);

Solution 2 - Objective C

Normally, callbacks in objective C are done with delegates. Here's an example of a custom delegate implementation;

Header File:

@interface MyClass : NSObject {
    id delegate;
- (void)setDelegate:(id)delegate;
- (void)doSomething;

@interface NSObject(MyDelegateMethods)
- (void)myClassWillDoSomething:(MyClass *)myClass;
- (void)myClassDidDoSomething:(MyClass *)myClass;

Implementation (.m) File

@implementation MyClass
- (void)setDelegate:(id)aDelegate {
    delegate = aDelegate; /// Not retained

- (void)doSomething {
    [delegate myClassWillDoSomething:self];
    /* DO SOMETHING */
    [delegate myClassDidDoSomething:self];

That illustrates the general approach. You make a category on NSObject that declares the names of your callback methods. NSObject doesn't actually implement these methods. This type of category is called an informal protocol, you're just saying that many objects might implement these methods. They're a way to forward declare the type signature of the selector.

Next you have some object be the delegate of "MyClass" and MyClass calls the delegate methods on the delegate as appropriate. If your delegate callbacks are optional, you'll typically guard them at the dispatch site with something like "if ([delegate respondsToSelector:@selector(myClassWillDoSomething:)) {". In my example, the delegate is required to implement both methods.

Instead of an informal protocol, you can also use a formal protocol defined with @protocol. If you do that, you'd change the type of the delegate setter, and instance variable to be "id <MyClassDelegate>" instead of just "id".

Also, you'll notice the delegate is not retained. This is typically done because the object that "owns" instances of "MyClass" is typically also the delegate. If MyClass retained its delegate, then there would be a retain cycle. It's a good idea in the dealloc method of a class that that has a MyClass instance and is its delegate to clear that delegate reference since it's a weak back pointer. Otherwise if something is keeping the MyClass instance alive, you'll have a dangling pointer.

Solution 3 - Objective C

Here's an example that keeps the concepts of delegates out, and just does a raw call back.

@interface Foo : NSObject {
- (void)doSomethingAndNotifyObject:(id)object withSelector:(SEL)selector;

@interface Bar : NSObject {

@implementation Foo
- (void)doSomethingAndNotifyObject:(id)object withSelector:(SEL)selector {
    /* do lots of stuff */
    [object performSelector:selector withObject:self];

@implementation Bar
- (void)aMethod {
    Foo *foo = [[[Foo alloc] init] autorelease];
    [foo doSomethingAndNotifyObject:self withSelector:@selector(fooIsDone:)];

- (void)fooIsDone:(id)sender {
    NSLog(@"Foo Is Done!");

Typically the method -[Foo doSomethingAndNotifyObject:withSelector:] would be asynchronous which would make the callback more useful than it is here.

Solution 4 - Objective C

To keep this question up-to-date, iOS 5.0's introduction of ARC means this can be achieved using Blocks even more concisely:

@interface Robot: NSObject
+ (void)sayHi:(void(^)(NSString *))callback;

@implementation Robot
+ (void)sayHi:(void(^)(NSString *))callback {
    // Return a message to the callback
    callback(@"Hello to you too!");

[Robot sayHi:^(NSString *reply){  NSLog(@"%@", reply);}];

There's always F****ng Block Syntax if you ever forget Objective-C's Block syntax.

Solution 5 - Objective C

CallBack: There are 4 types of callback in Objective C

  1. Selector type : You can see NSTimer,UIPangesture are the examples of Selector callback. Used for very limited execution of code.

  2. Delegate Type : Common and most used in Apple framework. UITableViewDelegate, NSNURLConnectionDelegate. They are usually used to show Downloading many images from server asynchronously etc.

  3. NSNotifications : NotificationCenter is one of features of Objective C which used to notify many receiptants at time when event occur.

  4. Blocks : Blocks are more commonly used in Objective C programming. It is great feature and used for executing chunk of code. You can also refer tutorial to understand : Blocks tutorial

Please let me if any other answer for it. I will appreciate it.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReachConnectionView Question on Stackoverflow
Solution 1 - Objective CJens AytonView Answer on Stackoverflow
Solution 2 - Objective CJon HessView Answer on Stackoverflow
Solution 3 - Objective CJon HessView Answer on Stackoverflow
Solution 4 - Objective CRyan BrodieView Answer on Stackoverflow
Solution 5 - Objective CAnil GuptaView Answer on Stackoverflow