objective-c - 在 Objective C 中实现相同协议(protocol)的类之间共享公共(public)方法实现

标签 objective-c

我有一个协议(protocol)。

我的协议(protocol).h:

@protocol MyProtocol
  @property(nonatomic, retain) NSString* someString;
  - (void)doesSomethingWithSomeString;
@end

还有 2 个实现相同协议(protocol)的类。由于某种原因,这两个类不能继承自同一个基类。例如。其中 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 的调用委托(delegate)给它。通常,这可能是一种很好的方法,尤其是在方法很长的情况下。

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

因此,虽然委托(delegate)给第三类是实现此目的的一种方法,但需要大量样板委托(delegate)包装代码来处理第三类中的许多短 1-2 方法。即,高样板委托(delegate)代码与实际代码的比例。

另一点是,由于这是一个模型类,公共(public)代码主要作用于 ivars/properties,委托(delegate)类最终将编写得几乎像全局 C 函数一样。

最佳答案

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

关于objective-c - 在 Objective C 中实现相同协议(protocol)的类之间共享公共(public)方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3262125/

相关文章:

objective-c - 后台实时摄像头(ios)

iphone - 自定义导航 Controller iOS 6 的问题

ios - 检查 ios 中的位置

objective-c - loadNibNamed :owner:options crashing app after conversion to ARC

iOS - 从后台处理远程推送通知。前景

objective-c - NSPopUpButtonCell 与 NSTableView 中的分层菜单

ios - 基于SQLite的核心数据: Drop indexes to reduce size and recreate them later

objective-c - 全屏播放视频时(Xcode 6)UIWebView打破约束

objective-c - 如何使状态项的标题成为图像而不是文本?

objective-c - 是否有相当于 Smalltalk 的#copyWithout : in Cocoa’s collection classes?