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.
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
@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