I have an Objective-C class that implements a node for a data tree. Its properties are read-only to the public while a private extension of the class (not shown here) implements the properties’ setters so a manager class can create the tree.
// Interface
@interface DataSet : NSObject {
NSString *name;
NSString *data;
@private
DataSet *parent;
NSMutableArray *children;
}
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, copy) NSString *data;
I want to implement a custom getter for one of the properties that, if the property is nil, will walk up the tree until it finds an ancestor node that has a non-nil value for that property.
My problem is implementing the getter without causing an infinite recursion of the getter calling itself.
// Implementation
@interface DataSet ()
@property (nonatomic, retain) DataSet *parent;
@property (nonatomic, retain) NSMutableArray *children;
@end
@implementation DataSet
@synthesize name;
// do not @synthesize data
@synthesize parent, children;
// custom getter walks up tree to find first non-nil 'data' property
- (NSString*) data {
NSString *result = nil;
DataSet *set = self;
while (set != nil && result == nil) {
result = [set data]; // <=== INFINITE RECURSION HERE
set = set.parent;
}
return result;
}
I’ve searched through this and other forums but haven’t found any examples of what I’m trying to do here. Anyone have any suggestions?
Also, should the last line in the getter be
return [result copy];
?
Hmmm, I think you want something like this:
Hmmm, actually seeing as you have a
datavariable containing some textural data, it could be done like this:So each instance of DataSet doesn’t need to have a loop. All they do is check with their immediate parent. This way if you have a data graph of A -> B -> C -> D and execute
[D data];the D will check itself and then as C, which will check itself and then as B, which will check itself and then ask A. You will get back the first successful non-nil value for result.