Objective-C: Make private property public with Objective-C category

只谈情不闲聊 提交于 2019-12-13 04:20:14

问题


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.

Is there any way to accomplish this, possibly via Objective-C category?

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.


回答1:


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.




回答2:


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

@interface FTGAnimal ()

@property (nonatomic, strong) FTGFood *food;

@end

@implementation FTGAnimal

@end

In your FTGAnimalTests.m, you can do like this

@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


来源:https://stackoverflow.com/questions/24197579/objective-c-make-private-property-public-with-objective-c-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!