问题
I want to prepare small static library for below classes in objective-c : Class A, Class B, Class C. I want to include these classes in static library. Now Class A can access public members of methods of Class B or Class C.
Now When I integrate above library in other project, I prepare Class D which can access only Class A and Class B Not Class C. How can I do this ?
My other doubt is assume that NSString *isValid is declared in Class B.
I want that above variable can be accessed from Class A and Class C I mean included files of library can access above variable.
But from outside library above variable can't be accessed. How can make it private so that it can be accessed within the library itself and not outside the library ?
Thanks for help !
回答1:
You can make public methods only visible to your static library but invisible out side of it.
Here is how to do it.
1) Create a header file to be used outside of your library
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
@property(nonatomic,readwrite)BOOL publicProperty;
-(void)publicMethod;
@end
2) Create a category to be only used internally by the static library
#import "ClassA.h"
@interface ClassA (Internal)
@property(nonatomic,readwrite)BOOL privateProperty;
-(void)privateMethod;
@end
Note Name this file: "ClassA+Internal.h"
3) Declare your private properties and methods again in the .m file
#import "ClassA.h"
@interface ClassA ()
@property(nonatomic,readwrite)BOOL privateProperty;
-(void)privateMethod;
@end
@implementation ClassA
@synthesize publicProperty;
@synthesize privateProperty;
//...
@end
Using private properties and methods inside the static library
In your ClassB.m file import header file of the ClassA category
#import "ClassB.h"
#import "ClassA.h"
#import "ClassA+Internal.h"
Now you have access to the private properties and methods of ClassA
Creating static library without private properties and methods
When you create you static library keep the "ClassA+Internal.h" category header file inside "private" or "project" headers section of "Build Phases","Copy Headers"
This way when you build your static library the ClassA+Internal.h category will be inaccessible to the outside.
回答2:
As far as I know, there is no way in Obj-C to protect access to public members like you need it. A common approach is simply not to include the methods and ivars in the header file that you are shipping with the static library. For compiling the library yourself, you must of course use your complete private header.
Note that this does not work for Objective-C++ where the class structure must be known to the client of the library at compile time.
来源:https://stackoverflow.com/questions/12000571/how-can-i-make-it-private-members-or-methods-of-class-so-that-it-can-be-accessed