Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Objective-C, how to access private property from category

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
like image 479
js_ Avatar asked Jul 19 '12 07:07

js_


People also ask

What is category in Objective-C with example?

A category can be declared for any class, even if you don't have the original implementation source code. Any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class.

What is a property in Objective-C?

Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.

What is Ivar Objective-C?

Objective-C allows you to set four levels of scope for an instance variable as follows: @private - accessible only within the class that declares it. @protected - accessible within the class that declares it and all subclasses. This is the default.


1 Answers

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.

like image 55
lawicko Avatar answered Nov 15 '22 15:11

lawicko