18

I want to access private property of a class from its category.

But to access private property, I have to redeclare the same private property in category.
If I don't redeclare, I get a compile error, Property '<property name>' not found on object of type '<class name> *'.

Is this correct way to access private property of class from category?
And are there better ways to do this?

The following code is the code which private property is redeclared in category:

ClassA.h

@interface ClassA : NSObject
-(void)method1;
@end

ClassA.m

#import "ClassA.h"

// private property
@interface ClassA()
@property (nonatomic) NSString *s;
@end

@implementation ClassA
@synthesize s;

-(void)method1
{
    self.s = @"a";
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - method1", self.s]);
}
@end

ClassA+Category.h

#import "ClassA.h"

@interface ClassA(Category)
-(void)method2;
@end

ClassA+Category.m

#import "ClassA+Category.h"

// redeclare private property
@interface ClassA()
@property(nonatomic) NSString *s;
@end

@implementation ClassA(Category)

-(void)method2
{
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - method2", self.s]);
}
@end


Is is good way to create a file(ClassA+Private.m) for private property and import it from ClassA.m and ClassA+Category.m:

ClassA+Private.m

@interface ClassA()
@property(nonatomic) NSString *s;
@end

1 Answer 1

13

The best way to solve this is to create ClassA+Private.h and import it in ClassA.m and Category.m. Mind the h at the end, you only need to declare your private properties and methods there, the definition is better kept in ClassA.m.

6
  • 3
    I'd say it would be better to import ClassA+Private.h in the .m only. Placing ClassA+Private.h in ClassA.h makes the properties visible to all classes that import ClassA.h which defeats the purpose. Jul 19, 2012 at 9:33
  • Also, I think ClassA+Protected.h would be more accurate than ClassA+Private.h. Jul 19, 2012 at 9:33
  • Agreed with 1 and edited the answer. As for protected, I agree this makes eyes bleed but for people not coming from other programming languages this probably doesn't make any difference, so I just used the naming suggested by author of the question.
    – lawicko
    Jul 19, 2012 at 9:59
  • It think some time has passed and it's fair to say 'Private' is now more of a convention.
    – fatuhoku
    Feb 14, 2015 at 21:47
  • @lawicko ClassA+Private.h in a separate file ?
    – The iCoder
    Feb 21, 2018 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.