【发布时间】:2010-07-16 05:18:13
【问题描述】:
我有一个协议。
MyProtocol.h:
@protocol MyProtocol
@property(nonatomic, retain) NSString* someString;
- (void)doesSomethingWithSomeString;
@end
还有 2 个实现相同协议的类。由于某种原因,这两个类不能从同一个基类继承。例如。其中 1 个可能需要从 NSManagedObject(Apple 的 Cocoa 框架中的核心数据类)继承,而另一个则不需要。
Class1.h:
@interface Class1: NSObject<MyProtocol> {
NSString* someString;
}
//Some method declarations
@end
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
Class2.h:
@interface Class2: SomeOtherClass<MyProtocol> {
NSString* someString;
}
//Some method declarations
@end
Class2.m
@implementation Class2
@synthesize someString;
// This is exactly the same as -doesSomethingWithSomeString in Class1.
- (void)doesSomethingWithSomeString {
//don't use property here to focus on topic
return [[self someString] capitalizedString];
}
//Method definitions for methods declared in Class2
@end
如何避免重复 -doesSomethingWithSomeString? (我想我需要多个类的类别)。
更新:
有一些关于辅助类的建议,并将 Class1 和 Class2 的调用委托给它。一般来说,这可能是一个好方法,尤其是在方法很长的情况下。
在这种情况下,我正在查看从 NSObject 继承的 Class1 和从 NSManagedObject 继承的 Class2。后者是 Class2 必须从其子类化的基类,作为 Apple Core Data 框架中的模型/实体。
因此,虽然委托给第三类是一种方法,但对于第三类中的许多短 1-2 方法,需要大量样板委托包装代码。即高样板委托代码与实际代码配给。
另外一点是,由于这是一个模型类,公共代码主要作用于 ivars/properties,委托类最终会像全局 C 函数一样编写..
【问题讨论】:
标签: objective-c