I need to be able to create an interface like you create in C# to enforce a group of classes to implement certain methods. Is this possible in objective c?
You can create a protocol. it would look something like this: in MyProtocol.h:
@protocol MyProtocol
-(void)myMethod;
-(void)myMethod2;
@end
in MyClass.h
#import "MyProtocol.h"
@interface MyClass : NSObject<MyProtocol>
@end
If you want to receive objects of a given protocol, you can do so like this:
id<MyProtocol> var;
or
NSObject<MyProtocol> *var;
more info here
You declare a "protocol" (Objective-C's interfaces) using
@protocol MyProtocol <BaseProtocol1,...,BaseProtocolN>
//methods and properties
@end
where <BaseProtocol>
is optional and indicates that MyProtocol
"inherits" BaseProtocol
's interface. The NSObject
protocol is useful in this context because it allows you to use
@protocol MyProtocol <NSObject>
//...
@end
to indicate (when appropriate) that conforming instances of MyProtocol
have the standard NSObject
methods as well (e.g. -retain/-release
, etc.).
You then declare that a class "conforms" to a protocol:
@interface MyClass : NSObject <MyProtocol,...,OtherProtocols>
{}
@end
And you can test whether an instance conforms to a protocol:
id myInstance = ...; //some object instance
if([myInstance conformsToProtocol:@protocol(MyProtocol)]) {
// myInstance conforms to MyProtocol
}
You can further silence compiler warnings by declaring that a variable holds instances that conform to a protocol (note that Objective-C's dynamic nature prevents the compiler from verifying that contract and you can still get runtime errors by assigning a non-conforming instance to the variable):
id<MyProtocol> o;
In this case, the compiler will complain if you send [o retain]
without MyProtocol
conforming to the NSObject
protocol. You can silence these warnings by declaring MyProtocol
as conforming to NSObject
as described above or by delcaring o
as
NSObject<MyProtocol> o;
Since NSObject
is not the only root object in Cocoa (i.e. NSProxy
does not inherit from NSObject
), it's not necessarily true that all instances conforming to MyProtocol
also conform to NSObject
. If you know that they do, you can declare MyProtocol
as conforming to NSObject
.
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