Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

objective c - Hiding properties from public framework headers, but leaving available internally

I need to have property in class that is excluded from public framework headers, but it is available for use internally in other framework classes. What I did right now is:

MyClass.h:

@interface MyClass: NSObject

@end

MyClass+Internal.h

@interface MyClass (Internal)
@property (nonatomic, copy) NSString *mySecretProperty;
@end

MyClass.m

#import "MyClass.h"
#import "MyClass+Internal.h"

@interface MyClass ()
@property (nonatomic, copy) NSString *mySecretProperty;
@end

@implementation MyClass
@end  

And I can use private property like:

MyOtherClass.m:

#import "MyClass.h"
#import "MyClass+Internal.h"

@implementation MyOtherClass
- (void)test {
    MyClass *myClass = [MyClass new];
    NSLog(@"%@", myClass.mySecretProperty)
}
@end 

But what I don't like about this setup is that I have duplicate declaration of property in my Internal Category and inside of anonymous Category. Is there a way to improve this setup?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you could do with the class extension only, there is no need to use a category. The quick fix would be to remove the category name from the parenthesis, transforming it into the class extension, then remove the class extension declaration from the .m file. After this you only import the extension header in your framework classes and you make sure it is a private header of your framework.

MyClass.h

@interface MyClass: NSObject

@end

MyClass+Internal.h

#import "MyClass.h"

@interface MyClass ()
@property (nonatomic, copy) NSString *mySecretProperty;
@end

MyClass.m

#import "MyClass.h"
#import "MyClass+Internal.h"

@implementation MyClass
@end

MyOtherClass.m:

#import "MyClass.h"
#import "MyClass+Internal.h"

@implementation MyOtherClass
- (void)test {
    MyClass *myClass = [MyClass new];
    NSLog(@"%@", myClass.mySecretProperty)
}
@end 

The key is understanding the difference between categories and class extensions, see here: https://stackoverflow.com/a/4540582/703809


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...