【问题标题】:Sharing common method implementation between classes implementing the same protocol in Objective C在 Objective C 中实现相同协议的类之间共享公共方法实现
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 添加了有关使用助手/委托类的更新。
    【解决方案2】:

    这种情况表明您的Class1Class2 没有完全分解到只处理一个问题的类中。您有一个共同的实现这一事实表明应该有第三个类提供该实现,并且Class1Class2 可以将这个问题委托给它。换句话说,这是组合而不是继承的情况。

    更新 如果委托给一个类没有意义,请不要忘记 Objective-C 是 C 的超集。没有什么能阻止你实现一个 C 函数库,你可以从两个类中调用它来封装常见行为.如果您致力于像 NSAssert et al. 这样的便利,您始终可以将它们实现为实用程序类或 NSObject 上的类别的类方法。

    【讨论】:

    • 添加了有关使用助手/委托类的更新。
    【解决方案3】:

    我个人认为这应该被复制。您最终可能需要自定义其中一个,然后您会为防止重复所做的所有工作而烦恼。任何大的东西都可以归入您正在使用的对象的类别中,类似于 capitalizedString 内部发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 2018-10-31
      • 2015-06-06
      • 1970-01-01
      • 2015-01-31
      • 2011-08-14
      相关资源
      最近更新 更多