Search code examples
objective-cooppublicprivate-members

Private v/s Public class properties in Objective C


Trying to make my OOP fundamentals strong based of objective C. Sorry if my explanation is too long. I have 3 classes in my app as Class A, Class B and Class C objective C classes. I have a property of class A in my implementation of class B i.e. it makes private property of class B.

// implementation Class B
@interface ClassB ()
  @property (nonatomic, strong) ClassA *classA;
@end

I create an instance of class B in one of my class C methods and try to access class A property through class B's instance in class C.

// implementation Class C
@interface ClassC ()
  @property (nonatomic, strong) ClassB *classB;
@end

@implementation ClassC
- (void)someMethod
{
  NSString *string = [[NSString alloc] init];
  classB = [[ClassB alloc] init];
  string = classB.classA.displayString; //get an error here - ClassB doesn't have classA.
}
@end

To avoid the error I moved the classA property from implementation to header in ClassB.

// header Class B
@interface ClassB : NSObject
  @property (nonatomic, strong) ClassA *classA;
@end

But I am worried that anybody class can create an instance of class B, access classA property and can then use/modify the properties which are part of class A.

Question: Is it a good style to move the classA property to the header file of Class B so I can use it in Class C or should I create a method in Class B which returns me whatever I need from class A? Something like:

@implementation ClassB
- (NSString*)displayStringOfClassA
{
  classA = [[ClassA alloc] init];
  return self.classA.displayString;
}
@end

Solution

  • I would suggest a readonly string property in ClassB.h.

    ClassB.h:

    @property (nonatomic, readonly) NSString *classAString;
    

    ClassB.m:

    - (NSString *) classAString
    {
       return self.classA.displayString;
    }
    

    This acts as a "getter" method for the particular string you need, and avoids others getting access to classA.

    Edit:

    Others suggested adding classA as a readonly property in ClassB.h. This will still allow modification of classA properties, it will only guarantee that classA is not reassigned to another ClassA instance.