简体   繁体   English

Objective-C:通过Objective-C类别公开私有财产

[英]Objective-C: Make private property public with Objective-C category

I am looking for a way to make a private property (declared in .m file within class extension) public so that it is accessible outside the class, without changing its original class . 我正在寻找一种公开私有属性(在类扩展名中的.m文件中声明)的方法,以便可以在类外部访问它, 而无需更改其原始类

Is there any way to accomplish this, possibly via Objective-C category? 有什么办法可以做到这一点,可能是通过Objective-C类吗?

I see from Apple documentation that category can be used, although not recommended, to redefine methods already in the original class, but I'm not sure if it can be used to make "existing" properties available to other classes. 从Apple文档中可以看到,尽管不建议使用该类别,但可以重新定义原始类中已经存在的方法,但是我不确定该类别是否可以用于使“现有”属性可供其他类使用。

This is indeed possible by using a category to surface the method. 通过使用类别浮出水面的方法,确实可以做到这一点。

@interface MyClass (Private)

@property (nonatomic, strong) NSObject *privatePropertyToExpose;
- (void) privateMethodIWantToUse;

@end

That's all it takes, just stick that somewhere where your calling class can see it and that will let you use the private method/property. 这就是全部,只需将其放在调用类可以看到的地方,即可使用私有方法/属性。

Yes, this is possible, and is a common trick to expose those property to test 是的,这是可能的,并且是将这些属性公开进行测试的常见技巧

So for example, you have this in your Animal.m file 例如,您在Animal.m文件中有此文件

@interface FTGAnimal ()

@property (nonatomic, strong) FTGFood *food;

@end

@implementation FTGAnimal

@end

In your FTGAnimalTests.m , you can do like this 在您的FTGAnimalTests.m中 ,您可以这样做

@interface FTGAnimal (FTGAnimalTests)

@property (nonatomic, strong) FTGFood *food;

@end

SPEC_BEGIN(FTGAnimalTests)

describe(@"FTGAnimalTests", ^{
    context(@"default context", ^{
        it(@"should initialize correct animal", ^{
            FTGAnimal *animal = [[FTGAnimal alloc] init];

            [[animal.food should] beMemberOfClass:[FTGFood class]];

        });
    });
});

SPEC_END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM