Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Class Extension for Selective Visibility in Objective-C

Would it make any sense to put class extensions in their own .h files and #import them selectively to get various levels of visibility for a class' methods and properties? If this is a bad idea (or would not work), why?

like image 537
Dan Rosenstark Avatar asked Aug 18 '11 16:08

Dan Rosenstark


1 Answers

It is a great idea and exactly why Class Extensions were designed (and why they are different than categories).

Namely, you can:

Foo.h

@interface Foo:NSObject
...public API here...
@property(readonly, copy) NSString *name;
@end

Foo_FrameworkOnly.h

@interface Foo()
@property(readwrite, copy) NSString *name;
@end

Foo.m

#import "Foo.h"
#import "Foo_FrameworkOnly.h"

@interface Foo()
... truly implementation private gunk, including properties go here ...
@end

@implementation Foo
@synthesize name = name_;
@end

And effectively have a property that is publicly readonly and privately read write for only the implementation files that import Foo_FrameworkOnly.h.

like image 199
bbum Avatar answered Oct 05 '22 22:10

bbum