How to perform call back functions in Objective-C?
I would just like to see some completed examples and I should understand it.
How to perform call back functions in Objective-C?
I would just like to see some completed examples and I should understand it.
Normally, callbacks in objective C are done with delegates. Here's an example of a custom delegate implementation;
Header File:
Implementation (.m) File
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.
To keep this question up-to-date, iOS 5.0's introduction of ARC means this can be achieved using Blocks even more concisely:
There's always F****ng Block Syntax if you ever forget Objective-C's Block syntax.
For completeness, since StackOverflow RSS just randomly resurrected the question for me, the other (newer) option is to use blocks:
CallBack: There are 4 types of callback in Objective C
Selector type : You can see NSTimer,UIPangesture are the examples of Selector callback. Used for very limited execution of code.
Delegate Type : Common and most used in Apple framework. UITableViewDelegate, NSNURLConnectionDelegate. They are usually used to show Downloading many images from server asynchronously etc.
Please let me if any other answer for it. I will appreciate it.
Here's an example that keeps the concepts of delegates out, and just does a raw call back.
Typically the method -[Foo doSomethingAndNotifyObject:withSelector:] would be asynchronous which would make the callback more useful than it is here.