0

I would like to ask you some opinion about what I'm doing. I know it works, but I'm not sure is proper to do what I'm doing.

I have a superclass Building that need to expose two NSString, name and description. No one should be able to modify those variables apart their subclasses.

To get this result I have created two public method on the base class:

@interface Building : NSObject 

- (NSString *)name;
- (NSString *)description;
@end

Then on each subclass I'm creating a private interface with name and description properties and let the magic happen.

@interface Barrack()
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *description;
@end

@implementation Barrack
@synthesize name, description;
...
@end

What you guys think about this?Is this a proper way to get this kind of result, anyone have better ideas about this topic? Thanks for your opinion.

Best,

Enrico

Enrico Bottani
  • 124
  • 1
  • 8

1 Answers1

3

Declare readonly properties in the interface, readwrite in the implementation class extension. No need for @synthesize. This is one of the main reason class extensions were added to Objective-C.

in Building.h

@interface Building : NSObject 
@property (nonatomic, strong, readonly) NSString *name;
@property (nonatomic, strong, readonly) NSString *description;
@end

In Barrack.m

@interface Barrack ()
@property (nonatomic, strong, readwrite) NSString *name;
@property (nonatomic, strong, readwrite) NSString *description;
@end

@implementation Barrack
...
@end
zaph
  • 111,848
  • 21
  • 189
  • 228
  • Thank for your input Zaph, but isn't this solution doing the same thing like mine? If you are not synthesizing the property the attributes are not used, correct? And also the readwrite attribute is used by default so is not needed in the private interface. Maybe I didn't express well my self, what I would like to discuss is the best option to create protected variables in Objective-C and show one implementation I used, and I would like to know how you guys deal with this problem. – Enrico Bottani Nov 14 '13 at 09:18
  • @Enrico Yes, it essentially does the same thing only using readonly and readwrite properties which is the current best practice. The current development tools auto-synthesize so that is no longer needed in most cases such as this. The readwrite property is needed because the public property is declared readonly. It must be redeclared readwrite in the implementation so setters can be used as opposed to directly accessing the underlying ivar. – zaph Nov 14 '13 at 13:44