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

Mat*_*art 13 implementation protocols objective-c categories

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

- (NSUInteger)length;
Run Code Online (Sandbox Code Playgroud)

还有其他一些方法.

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

@interface NSString (NSStringWithMyProtocol) <MyProtocol>
@end
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

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

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

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

完整代码:

协议:

@protocol MyProtocol <NSObject>

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

@end
Run Code Online (Sandbox Code Playgroud)

类别标题:

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

@interface NSString (MyProtocol) <MyProtocol>
@end
Run Code Online (Sandbox Code Playgroud)

类别实施:

@implementation NSString (MyProtocol)

- (void)myMethod {

}

@end
Run Code Online (Sandbox Code Playgroud)

这会导致以下警告.

Incomplete implementation

Method in protocol not implemented
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*ier 9

我无法重现这个问题.你可以发布演示它的代码吗?以下编译没有警告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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我添加了我的代码。我也看到有什么不同。您没有为类别定义实现。 (2认同)