Objective-C: Make private property public with Obj

2019-09-17 03:04发布

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.

2条回答
forever°为你锁心
2楼-- · 2019-09-17 03:15

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.

查看更多
迷人小祖宗
3楼-- · 2019-09-17 03:28

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
查看更多
登录 后发表回答