Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend protocols / delegates in Objective-C?

If i want to extend a class like AVAudioPlayer, whats the best way to also add another method to AVAudioPlayerDelegate?

Should I make a category for it, do I extend it?

If I extend it do I then also have to make sure to overwrite the actual delegate getter/setter? How would I extend the protocol?

The following gives me errors

@protocol AudioTrackDelegate : AVAudioPlayerDelegate {     - (void)foo; } @end  @interface AudioTrack : AVAudioPlayer { } @end 
like image 345
dizy Avatar asked Apr 09 '09 03:04

dizy


People also ask

How do I set delegates in Objective-C?

To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol. Then you could create an instance of MyClass and assign it as the web view's delegate: MyClass *instanceOfMyClass = [[MyClass alloc] init]; myWebView.

Does Objective-C have extensions?

Instead, Objective-C allows you to add your own methods to existing classes through categories and class extensions.

What does delegate mean in Objective-C?

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object—that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit—that is responding to a user event.

What is Objective-C protocol?

Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. This chapter describes the syntax to define a formal protocol, and explains how to mark a class interface as conforming to a protocol, which means that the class must implement the required methods.


1 Answers

The syntax for creating a protocol that implements another protocol is as such:

@protocol NewProtocol <OldProtocol> - (void)foo; @end 

If you want to call a method in NewProtocol on a pointer typed as OldProtocol you can either call respondsToSelector:

if ([object respondsToSelector:@selector(foo)])     [(id)object foo]; 

Or define stub methods as a category on NSObject:

@interface NSObject (NewProtocol) - (void)foo; @end @implementation NSObject (NewProtocol) - (void)foo { } @end 
like image 131
rpetrich Avatar answered Oct 14 '22 15:10

rpetrich