0

I have a property to an object instance in my class

@property(nonatomic, strong) MyObject *myObject;

And I expose a helper property.

@property(nonatomic, assign, readonly) BOOL hasMyObject

Which does

return self.myObject != nil;

I need hasMyObject to be KVO compliant (I am using RAC on it). To solve this I currently call:

- (void)app_setMyObject:(MyObject*)myObject
{
    [self willChangeValueForKey:@keypath(self.hasMyObject)];
    self.myObject = myObject;
    [self didChangeValueForKey:@keypath(self.hasMyObject)];
}

every time I set myObject.

In this way an observer can know when hasMyObject changes.
My question is:
1. Is this OK
2. Is there a better way to do it?


Why do I do this at all?
Why not just use myObject property?

It is an API design thing. The myObject property is internal and should not be exposed publicly and myObject is only set from within the class.

Karmeye
  • 1,399
  • 1
  • 8
  • 16

1 Answers1

3

There's a better way:

+ (NSSet *)keyPathsForValuesAffectingHasMyObject {
    return [NSSet setWithObject:@keypath(ClassName.new, myObject)];
}

Of course, ClassName.new is never actually evaluated (look at the expansion of @keypath), but it's the only way to get an instance keypath from a class method.

Ian Henry
  • 22,255
  • 4
  • 50
  • 61