Use Class Extension for Selective Visibility in Objective-C

时光怂恿深爱的人放手 提交于 2019-11-29 18:47:04

问题


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?


回答1:


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.




回答2:


Class extension (as opposed to subclassing) in Objective-C is accomplished with Categories. In Xcode, go to File > New > File and select Objective-C Category. It will ask you what to call the category and what class it should extend. You'll get a .h/.m pair in which to put your interface and implementation, respectively. If you want access to the features provided in your extension, just import its .h file.



来源:https://stackoverflow.com/questions/7110525/use-class-extension-for-selective-visibility-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!