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

Objective c 使类符合现有方法的类别协议,objective-c,protocols,implementation,categories,Objective C,Protocols,Implementation,Categories,我有一个协议名为MyProtocol。 MyProtocol有一个必需的方法: - (NSUInteger)length; 以及其他一些方法 现在我想让NSString类符合MyProtocol的类别。像这样: @interface NSString (NSStringWithMyProtocol) <MyProtocol> @end 这将导致以下警告 Incomplete implementation Method in protocol not implemented 在

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

- (NSUInteger)length;
以及其他一些方法

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

@interface NSString (NSStringWithMyProtocol) <MyProtocol>
@end
这将导致以下警告

Incomplete implementation

Method in protocol not implemented
在此屏幕截图中,您可以看到我的警告:

我尝试使用LLVMGCC4.2和Apple LLVM3.0编译器进行编译。 我还编译了xcode 4.0.2和xcode 4.2。
我在OSX.103.8.

你可能会认为这是一个黑客攻击,我不知道它是否会起作用,但是如何声明它为只读属性

如何?
@property (readonly, assign) NSUInteger length;

然后在实现您的类别时,将其设置为
@dynamic

我无法重现此问题。你能发布演示它的代码吗?以下在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;
}
#导入
@协议MyProtocol
-(整数)长度;
@结束
@接口NSString(NSStringWithMyProtocol)
@结束
int main(int argc,const char*argv[]{
@自动释放池{
id foo=@“foo”;
NSLog(@“%@”,foo);
}
返回0;
}

我们可以为一个获得者工作,但不能为设定者工作。没有表明这只是一个例子。无法谈论我的生产代码。是的。但这不仅解决了setter/getter类方法。正如我在前面的评论中提到的,我处理其他类和方法。我也看到了不同之处。您没有为该类别定义实现。显然,Clang在这方面比gcc严格得多。在绝大多数情况下,这是一件好事,但在本例中,我相信您已经将其推到了当前实现的边缘。我会针对叮当打开一个缺陷。我想我会签署这个作为正确答案。注意,只有当一个类已经实现了协议中定义的所有方法时,它才会起作用。类别实现不能与协议的部分实现一起存在。这个问题和答案对我很有帮助。我得到了同样的警告,但我的代码仍然编译并运行FWIW。
Incomplete implementation

Method in protocol not implemented
@property (readonly, assign) NSUInteger length;
#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;
}