gpt4 book ai didi

objective-c - 使类符合现有方法类别的协议(protocol)

转载 作者:太空狗 更新时间:2023-10-30 03:20:40 25 4
gpt4 key购买 nike

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

- (NSUInteger)length;

还有一些其他的方法。

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

@interface NSString (NSStringWithMyProtocol) <MyProtocol>
@end

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

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

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

  1. 使方法可选
  2. 指针调配
  3. 向符合协议(protocol)的类添加子类。然后省去实现。

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

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

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

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

完整代码:

协议(protocol):

@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

在这张截图中你可以看到我的警告: Screen shot

我尝试使用 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;
}

关于objective-c - 使类符合现有方法类别的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7255392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com