Search code examples
iosobjective-cscopeencapsulationprivate-members

Is there a way to allow certain classes to access private properties of certain other classes?


I have 2 classes that I want to be able to access each others properties, but I don't want those properties accessed from anywhere else. Is there a way to do this? Is the only way to accomplish this through subclassing? Is there no way to establish a "special" relationship between two classes?


Solution

  • If I understand your question, you effectively want class A and class B, which are unrelated by inheritance, to be aware of more innards than are publicly advertised?

    Say A has a property called innardsForB that only instances of B should access. You can use class extensions to declare the non-public interface to A.


    A.h

    @interface A:NSObject
    ... regular class goop here ...
    @end
    


    A-Private.h

    @interface A()
    @property(nonatomic, strong) Innards *innardsForB;
    @end
    


    A.m

    #import "A.h"
    #import "A-Private.h"
    
    @implementation A
    // because "A-Private.h" is #import'd, `innardsForB` will be automatically @synthesized
    ...
    @end
    


    B.m

    #import "B.h"
    #import "A-Private.h"
    
    @implementation B
    ...
    - (void)someMethod
    {
         A *a = [self someASomewhere];
         a.innardsForB = [[Innards alloc] initForMeaning:@(42)];
    }