声明私有属性的方法很简单。
您声明在.m文件中声明的扩展名。
假设我想声明受保护的属性并从类和子类访问它。
这就是我的尝试:
//
// BGGoogleMap+protected.h
//
//
#import "BGGoogleMap.h"
@interface BGGoogleMap ()
@property (strong,nonatomic) NSString * protectedHello;
@end
那是编译。然后我补充道:
#import "BGGoogleMap+protected.h"
@implementation BGGoogleMap ()
-(NSString *) protectedHello
{
return _
}
@end
问题开始了。我似乎无法在原始的.m文件之外实现类扩展。 Xcode将需要一些内容。
如果我这样做
#import "BGGoogleMap+protected.h"
@implementation BGGoogleMap (protected)
-(NSString *) protectedHello
{
return _
}
@end
我无法访问BGGoogleMap + protected.h中声明的_protectedHello的ivar
当然我可以使用常规类别而不是扩展名,但这意味着我不能拥有受保护的属性。
那我该怎么办?
答案 0 :(得分:7)
The Objective-C Programming Language说:
类扩展类似于匿名类别,除了它们声明的方法必须在相应类的主
@implementation
块中实现。
因此,您可以在类的主@implementation
中实现类扩展的方法。这是最简单的解决方案。
更复杂的解决方案是在类别中声明“受保护”的消息和属性,并在类扩展中声明该类别的任何实例变量。这是类别:
BGGoogleMap+protected.h
#import "BGGoogleMap.h"
@interface BGGoogleMap (protected)
@property (nonatomic) NSString * protectedHello;
@end
由于某个类别无法添加实例变量来保存protectedHello
,因此我们还需要一个类扩展:
#import "BGGoogleMap.h"
@interface BGGoogleMap () {
NSString *_protectedHello;
}
@end
我们需要在主@implementation
文件中包含类扩展,以便编译器在.o
文件中发出实例变量:
BGGoogleMap.m
#import "BGGoogleMap.h"
#import "BGGoogleMap_protectedInstanceVariables.h"
@implementation BGGoogleMap
...
我们需要在类@implementation
文件中包含类扩展,以便类别方法可以访问实例变量。由于我们在类别中声明了protectedHello
属性,因此编译器将不合成setter和getter方法。我们必须手工编写:
BGGoogleMap+protected.m
#import "BGGoogleMap+protected.h"
@implementation BGGoogleMap (protected)
- (void)setProtectedHello:(NSString *)newValue {
_protectedHello = newValue; // assuming ARC
}
- (NSString *)protectedHello {
return _protectedHello;
}
@end
子类应导入BGGoogleMap+protected.h
以便能够使用protectedHello
属性。它们不应导入BGGoogleMap_protectedInstanceVariables.h
,因为实例变量应该被视为对基类的私有。如果您发送的是没有源代码的静态库,并且您希望库的用户能够继承BGGoogleMap
,请发送BGGoogleMap.h
和BGGoogleMap+protected.h
标头,但不要发送{ {1}}标题。
答案 1 :(得分:2)
我希望我能告诉你,但你不能。有关详细信息,请参阅此问题:Protected methods in Objective-C。
答案 2 :(得分:0)
我不确定,你想做什么? OOPS概念中的数据抽象被黑客攻击或破解?
扩展程序用于添加属性。您已成功添加私有财产,如
#import "BGGoogleMap.h"
@interface BGGoogleMap ()
@property (strong,nonatomic) NSString * protectedHello;
@end
你在做什么?
#import "BGGoogleMap+protected.h"
@implementation BGGoogleMap ()
-(NSString *) protectedHello
{
return _
}
@end
你已经扩展了一个班级,现在你再次实施同一个班级!两次!!!并且类别仅附带.h文件。我猜你自己创建了一个.m文件,这是不可接受的。
私有属性不能在类外部访问,只能从基类或子类访问。这就是错误。
I can't implement class extension outside the original .m files it seems.
是的,这是Objective-c的抽象和数据隐藏!!!