我有一个协议。
MyProtocol.h:
@protocol MyProtocol
@property(nonatomic, retain) NSString* someString;
- (void)doesSomethingWithSomeString;
@end
Run Code Online (Sandbox Code Playgroud)
和2个实现相同协议的类。由于某些原因,这两个类不能从相同的基类继承。例如,其中之一可能需要继承自NSManagedObject(Apple Cocoa框架中的Core Data类),而另一个则不需要。
Class1.h:
@interface Class1: NSObject<MyProtocol> {
NSString* someString;
}
//Some method declarations
@end
Run Code Online (Sandbox Code Playgroud)
Class1.m
@implementation Class1
@synthesize someString;
- (void)doesSomethingWithSomeString {
//don't use property here to focus on topic
return [[self someString] capitalizedString];
}
//Method definitions for methods declared in Class1
@end
Run Code Online (Sandbox Code Playgroud)
Class2.h:
@interface Class2: SomeOtherClass<MyProtocol> {
NSString* someString;
}
//Some method declarations
@end
Run Code Online (Sandbox Code Playgroud)
Class2.m
@implementation Class2
@synthesize someString;
// This is exactly the same as -doesSomethingWithSomeString …Run Code Online (Sandbox Code Playgroud) objective-c ×1