我有以下协议(protocol):
@protocol MyProtocol
@property (nonatomic, retain) NSObject *myProtocolProperty;
-(void) myProtocolMethod;
@end
我有以下类(class):
@interface MyClass : NSObject {
}
@end
我声明了一个类扩展,我必须在这里重新声明我的协议(protocol)属性,否则我无法使用类的其余部分来实现它们。
@interface()<MyProtocol>
@property (nonatomic, retain) NSObject *myExtensionProperty;
/*
* This redeclaration is required or my @synthesize myProtocolProperty fails
*/
@property (nonatomic, retain) NSObject *myProtocolProperty;
- (void) myExtensionMethod;
@end
@implementation MyClass
@synthesize myProtocolProperty = _myProtocolProperty;
@synthesize myExtensionProperty = _myExtensionProperty;
- (void) myProtocolMethod {
}
- (void) myExtensionMethod {
}
- (void) useMyConsumer {
[[[MyConsumer new] autorelease] consumeMyClassWithMyProtocol:self];
}
@end
MyConsumer 只会从 MyClass 调用,因此我不希望任何其他类看到 MyClass 在 MyProtocol 上实现方法,因为它们不是公共(public) API。同样,我不希望 MyConsumer 看到 MyClass 中的类扩展。
@interface MyConsumer : NSObject {
}
@end
@implementation MyConsumer
- (void) consumeMyClassWithMyProtocol: (MyClass<MyProtocol> *) myClassWithMyProtocol {
myClassWithMyProtocol.myProtocolProperty; // works, yay!
[myClassWithMyProtocol myProtocolMethod]; // works, yay!
myClassWithMyProtocol.myExtensionProperty; // compiler error, yay!
[myClassWithMyProtocol myExtensionMethod]; // compiler warning, yay!
}
@end
有什么方法可以避免在我的类扩展中重新声明 MyProtocol 中的属性,以便私下实现 MyProtocol?
最佳答案
您所说的“匿名类别”实际上被称为 class extension ,并用于在实现文件中声明私有(private)功能。最后一部分很重要,因为这意味着其他类将无法看到您放入类扩展中的声明(并且它们将无法看到您的类实现了 MyProtocol
的方法)。这也可能是 @synthesize
的原因。在没有重新声明属性的情况下失败。
相反,在类的接口(interface)中声明您对协议(protocol)的一致性,并添加您想要公开的任何方法:
@interface MyClass : NSObject <MyProtocol> {
}
// public methods and properties go here
@end
如果您将协议(protocol)声明添加到接口(interface)中,那么您的使用者也无需显式指定它。您的消费者方法可以使用以下签名:
- (void) consumeMyClassWithMyProtocol: (MyClass *) myClassWithMyProtocol;
编辑:听起来您正在寻找一种有选择地公开私有(private)功能的方法。首先,我会尝试考虑一种不同的架构来实现您想要完成的任务,因为接下来将是一个相当令人不愉快的解决方案,如果一切都是公共(public)或私有(private)的,那么通常更好的 OOP。
话虽如此,苹果通常通过为相关类提供一个单独的头文件来解决这个问题,该头文件声明应该可见的方法。因此,您将拥有类接口(interface),在其中公开应完全公开的所有内容:// MyClass.h
@interface MyClass : NSObject {
}
@end
还有一个单独的 header ,您可以在其中声明伪私有(private)内容的类别:
// MyClass+Private.h
#import "MyClass.h"
@interface MyClass (Private) <MyProtocol>
- (void)mySortaPrivateMethod;
@end
MyClass.m
将实现这两个文件中的所有内容,并且仍然可以具有类扩展:
// MyClass.m
#import "MyClass.h"
#import "MyClass+Private.h"
@interface MyClass ()
- (void)myClassExtensionMethod;
@end
@implementation MyClass
// everything can go here
@end
然后您的消费者将包括 MyClass+Private.h
这样它就可以看到那里的声明,而其他人只需使用 MyClass.h
.
关于objective-c - 引用在协议(protocol)中声明并在匿名类别中实现的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4847542/