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
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.
Instead, Objective-C allows you to add your own methods to existing classes through categories and class extensions.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With