Objective-C public get set method for private property

2.7k views Asked by At

I wonder if it is possible to use @synthesize on a private @property so that the get/set methods have public access.

Right now my code looks something like this

SomeClass.h

#import <Foundation/Foundation.h>
@interface SomeClass : NSObject
{
    @private
    int somePrivateVariable;
}
@end

SomeClass.m

#import "SomeClass.h"
@interface SomeClass ()
@property int somePrivateVariable;
@end

@implementation
@synthesize somePrivateVariable;
@end

Then in some outside function I want to be able to write:

#import "SomeClass.h"
SomeClass *someClass = [[SomeClass alloc] init];
[someClass setSomePrivateVariable:1337];  // set the var
NSLog("value: %i", [someClass getSomePrivateVariable]); // get the var

I know that I can just create my own get/set methods in the header file but I would enjoy using the @synthesize very much more.

1

There are 1 answers

0
Jon Shier On BEST ANSWER

If you want a public property to mirror a private one, just override the public property's getter and setter and return the private one.

@interface Test : NSObject

@property NSObject *publicObject;

@end

Then, in the implementation:

@interface Test ()

@property NSObject *privateObject;

@end

@implementation Test

- (NSObject *)publicObject
{
    return self.privateObject;
}

- (void)setPublicObject:(NSObject *)publicObject
{
    self.privateObject = publicObject;
}

@end