0

How exactly should attributes be declared if they are needed to be private and the language supports automatic getter/setter method creation?

Is the only way to override the automatically created getter or setter as needed?

some_id
  • 29,466
  • 62
  • 182
  • 304

1 Answers1

3

In the top of the .m (implementation) file:

// Private category on your class, declared at top of implementation file.
@interface MyClass ()
@property (nonatomic, copy) NSString * privateString;
@end

@implementation
... 
@end

These "private properties" are visible only within your implementation. Please note that ObjC has no facility for runtime access restriction. Other objects can still call your private getters and setters if they want to (although this will generate compiler warnings).

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
  • Thanks, yes I know this. My question is more on a design level. If it is said to be bad design to declare attributes in a header file, is the only way to access these via overridden getter/setter methods? – some_id Apr 03 '13 at 17:23
  • @Helium3: I don't quite follow. What's bad design about declaring (public) attributes in a header file? And what are you trying to avoid, exactly? – Ben Zotto Apr 03 '13 at 17:24
  • I guess what I am asking does not apply to Objective-C, will mark the question for deletion. – some_id Apr 03 '13 at 17:26
  • @Helium3: Maybe try giving an example of what you're thinking of? – Ben Zotto Apr 03 '13 at 17:27
  • @Helium3: Now you can not delete, Ben got votes. – Anoop Vaidya Apr 03 '13 at 17:30
  • Note that none of what Ben did was in the header file, nor would the storage or setters implied by `privateString` be visible outside the compilation unit. – bbum Apr 03 '13 at 17:34