为目标C中的类定义私有方法的最佳方法我刚开始编写Object-C,并且有Java背景,想知道写Objec-C程序是如何处理私有方法的。我理解可能有一些约定和习惯,并将这个问题看作是人们在目标C中使用的处理私有方法的最佳技术的聚合器。在发帖时,请为您的方法提供一个论据。为什么它是好的?它有哪些缺点(据你所知),以及你如何处理它们?至于我到目前为止的发现。可以使用类别[例如MyClass(私有)]在MyClass.m文件中定义为分组私有方法。这种方法有两个问题:Xcode(以及编译器?)不检查是否在相应的@Implementation块中定义私有类别中的所有方法您必须将声明私有类别的@接口放在MyClass.m文件的开头,否则Xcode会发出类似于“Self可能不会响应消息”PrivateFoo“之类的消息。第一个问题可以用空范畴[例如MyClass()]。第二个让我很困扰。我希望在文件末尾附近实现(并定义)私有方法;我不知道这是否可能。
3 回答
智慧大石
TA贡献1946条经验 获得超3个赞
@implementation
@implementation
@implementation
).
static
@interface MONObject (PrivateStuff)
@implementation MONObject (PrivateStuff)...HERE...@end
@interface MONObject : NSObject// public declaration required for clients' visibility/use.@property (nonatomic, assign, readwrite) bool publicBool;// public declaration required for clients' visibility/use.- (void)publicMethod;@end
@interface MONObject ()@property (nonatomic, assign, readwrite) bool privateBool; // you can use a convention where the class name prefix is reserved// for private methods this can reduce accidental overriding: - (void)MONObject_privateMethod;@end// The potentially good thing about functions is that they are truly // inaccessible; They may not be overridden, accidentally used,// looked up via the objc runtime, and will often be eliminated from / backtraces. Unlike methods, they can also be inlined. If unused// (e.g. diagnostic omitted in release) or every use is inlined, // they may be removed from the binary:static void PrivateMethod(MONObject * pObject) { pObject.privateBool = true;}@implementation MONObject{ bool anIvar;}static void AnotherPrivateMethod(MONObject * pObject) { if (0 == pObject) { assert(0 && "invalid parameter"); return; } // if declared in the @implementation scope, you *could* access the // private ivars directly (although you should rarely do this): pObject->anIvar = true;}- (void)publicMethod{ // declared below -- but clang can see its declaration in this // translation: [self privateMethod];}// no declaration required.- (void)privateMethod{}- (void)MONObject_privateMethod{}@end
- 3 回答
- 0 关注
- 796 浏览
添加回答
举报
0/150
提交
取消