0

What's preferable and a clean solution for attributes in a class. Use categories (anonymous) or @private annotation in the interface definition (.h file). The attributes should not be inherited by other classes.

BR, mybecks

mybecks
  • 2,443
  • 8
  • 31
  • 43

2 Answers2

1

Categories and @private are two different things. Categories extend the classes where you can add methods to a class and @private is where other classes can't access your attributes directly and will have to use your accessors. If you want ivars that subclasses can't access, use @private in your interface.

@interface MyClass : NSObject
{
@private
int num; //private attribute where subclass can't access
}
TheAmateurProgrammer
  • 9,252
  • 8
  • 52
  • 71
1

First up read this to understand the @private modifier What does "@private" mean in Objective-C?

And then to answer your questions.

An anonymous category is called a class extension and this is what I use to keep my API's clean and to not publicly announce my ivars.

e.g

// .h
@interface MyClass : NSObject

@end

// .m
@interface MyClass ()

@property (nonatomic, strong) NSDate *someDateImWorkingWith;

@end

@implementation MyClass

@synthesize someDateImWorkingWith = _someDateImWorkingWith;

@end

As a result I have the NSDate *someDateImWorkingWith to use within my class but no one importing my header will even know it exists without doing a little bit of digging. This works well for me your milage may vary.

Community
  • 1
  • 1
Paul.s
  • 38,494
  • 5
  • 70
  • 88