繁体   English   中英

使类符合现有方法的类别协议

[英]Making class conform to protocol with category for existing methods

我有一个名为MyProtocol的协议。 MyProtocol有一个必需的方法:

- (NSUInteger)length;

还有其他一些方法。

现在我想让NSString类符合MyProtocol的类别。 像这样:

@interface NSString (NSStringWithMyProtocol) <MyProtocol>
@end

在这个类别中,我实现了除'length'方法之外的所有方法,因为我想要原始的NSString实现。 我不想在这个特定的类中覆盖它。

现在我收到警告,因为该类别中的MyProtocol实施不完整。

我知道有一些解决方案可以解决这个问题。

  1. 使方法可选
  2. 指针调酒
  3. 将子类添加到符合协议的类。 然后省略实施。

我不想使用这些选项,因为它们导致我的其余代码设计不好。
选项3很糟糕,因为现有的直接子类不符合协议。

有没有人知道如何在不实施长度方法的情况下删除警告?

注意:类,类别和协议只是示例。 我确实遇到了其他类我无法发布的问题。 谢谢

编辑:添加了第三个选项。

完整代码:

协议:

@protocol MyProtocol <NSObject>

- (void) myMethod;
- (NSInteger) length;

@end

类别标题:

#import <Foundation/Foundation.h>
#import "MyProtocol.h"

@interface NSString (MyProtocol) <MyProtocol>
@end

类别实施:

@implementation NSString (MyProtocol)

- (void)myMethod {

}

@end

这会导致以下警告。

Incomplete implementation

Method in protocol not implemented

在此屏幕截图中,您可以看到我的警告: 屏幕截图

我尝试使用LLVM GCC 4.2和Apple LLVM 3.0编译器进行编译。 我还编译了xcode 4.0.2和Xcode 4.2。 我在OS X 10.6.8上。

我无法重现这个问题。 你可以发布演示它的代码吗? 以下编译没有警告10.7。

#import <Foundation/Foundation.h>

@protocol MyProtocol <NSObject>
- (NSUInteger)length;
@end

@interface NSString (NSStringWithMyProtocol) <MyProtocol>
@end

int main (int argc, const char * argv[]) {
  @autoreleasepool {
    id<MyProtocol> foo = @"foo";
    NSLog(@"%@", foo);    
  }
  return 0;
}

您可能会认为这有点像黑客,我不知道它是否会起作用,但如何将其声明为只读属性

@property (readonly, assign) NSUInteger length;

然后在你的类别的实现中,使它成为@dynamic

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM