How to write methods that should only be used within the class itself and are able to access ivars
本问题已经有最佳答案,请猛点这里访问。
我有一个类,它有一些方法只能在类本身中使用。这些方法的存在是因为我对正在进行的图形工作有一个三步流程,但我只希望类的实例访问这些计算的最终结果,在一个简化的示例中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #import <Foundation/Foundation.h> @interface GraphicsWorld : NSObject @property(nonatomic, strong) NSMutableArray *objects; @property(nonatomic, strong) NSMutableArray *adjustedObjects /* three methods I'll never use outside of this class I want to find a way to get replace these methods. */ -(void) calcTranslation; -(void) calcRotation; -(void) calcPerspective; /* the one method I'll use outside of this class */ -(NSMutableArray *) getAdjustedObjects; @end |
我可以在实现之外为此定义C函数,但这样它们就不能访问属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #import <Foundation/Foundation.h> #import"GraphicsWorld.h" void calcTranslation() { // I'm useless because I can't access _objects. } void calcRotation() { // Hey, me too. } void calcPerspective() { // Wow, we have a lot in common. } @implementation GraphicsWorld -(NSMutableArray *) getAdjustedObjects { calcTranslation(); calcRotation(); calcPerspective(); return adjustedObjects; } @end |
无论方法是否声明为私有,都可以调用它;由于Objective-C的性质,隐藏方法很难。
隐藏函数要容易得多,只需声明它们
例如:
1 2 3 4 5 6 7 | void calcTranslation(GraphicsWorld *self) { // Access properties, instance variables, call instance methods etc. // by referencing self. You *must* include self to reference an // instance variable, e.g. self->ivar, as this is not a method the // self-> part is not inferred. } |
并称之为:
1 2 3 4 | -(NSMutableArray *) getAdjustedObjects { calcTranslation(self); ... |
除非我误解了你的问题,否则听起来你只是想隐藏你的方法,不让公众知道?如果是,只需从标题中删除它们。您不再需要在objc(xcode)中提前声明方法。编译器现在只会在内部找到它们。
除了