Jeremy L
Jeremy L

Reputation: 3810

Is there a way to have pseudo property in Objective-C?

Let say if there is already class properties of

@property (strong, nonatomic) JJNode *leftChild;
@property (strong, nonatomic) JJNode *rightChild;

and the app already makes extensive use of if (parent.leftChild) { ... } and parent.leftChild = newNode (both getter and setter).

But say, the class might work better if the left and right child can be represented by an NSMutableArray object, so that the class can support N-children in the future, and looping through the children is easier.

So it will be

@property (strong, nonatomic) NSMutableArray *childrenArray;

and in some cases, the children can be iterated by

for (JJNode *node in self.childrenArray) { ... }

But using this new array, can we still be able to keep on using parent.leftChild and parent.leftChild = newNode?

I wonder if it is a good practice, as it may seem like parent.leftChild and (JJNode *)[parent objectAtIndex: 0] are different objects, but in fact the same thing. But say if we go ahead and do it, can we have pseudo property to achieve that?

It seems that we can actually use @property (strong, nonatomic) JJNode *leftChild; and change the getter and setter to actually use the array, but there will be two extra instance variables. Can it be done without the ivars? Or can we define 2 methods so that parent.leftChild = newNode will actually invoke some setter method, and parent.leftChild will invoke a getter?

Upvotes: 1

Views: 108

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

Your properties are not limited to synthesized ones - in fact, they are no more than a pair of methods that follow a certain naming convention.

You can remove the @synthesize instructions for the leftChild and rightChild, and replace them with methods that get/set the first and the second elements of the NSArray that holds nodes in case when there are more than two.

Upvotes: 4

Related Questions