在实现目标C中相同协议的类之间共享通用方法实现

Hwe*_*Yar 5 objective-c

我有一个协议。

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 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
Run Code Online (Sandbox Code Playgroud)

如何避免重复-doesSomethingWithSomeString?(我想我需要多个类的类别)。

更新:

有一些关于帮助器类的建议,以及从Class1和Class2委托给它的调用。通常,这可能是一个很好的方法,尤其是如果方法很长。

在这种情况下,我正在研究从NSObject继承的Class1和从NSManagedObject继承的Class2。后者是Class2必须从其继承的基类,作为Apple Core Data框架内的模型/实体。

因此,虽然委派给第三类是做到这一点的一种方法,但对于第三类中的许多短1-2方法,需要有很多样板委派包装代码。即,将高级别的授权代码转换为实际的代码比率。

另一点是,由于这是一个模型类,所以通用代码主要作用于ivars / properties,因此委托类将最终像全局C函数一样编写。

小智 2

您可以创建一个辅助类,然后从 Class1 和 Class2 中使用它,然后只重复对辅助类上的方法的调用