Quantcast
Channel: Coding and Programing » cocoa
Viewing all articles
Browse latest Browse all 10

perform Callbacks in Objective-C

$
0
0

Problem And Question

I am a beginner programmer in Objective-C. Can anyone please tell me how to perform call back functions in Objective-C.

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

Thanks a lot

Best Solution And Answer

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;
@end

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


/// Message (.m) File
@implementation MyClass
- (void)setDelegate:(id)aDelegate {
    delegate = aDelegate; /// Not retained
}

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

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 ” 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.


Viewing all articles
Browse latest Browse all 10

Trending Articles