是否可以在Objective-C中将方法声明为私有方法? [英] Is it possible to declare a method as private in Objective-C?

查看:89
本文介绍了是否可以在Objective-C中将方法声明为私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Objective-C中将方法声明为私有方法?

Is it possible to declare a method as private in Objective-C?

推荐答案

如果您使用的是Objective-C 2.0,则创建供其他人调用的难"方法的最佳方法是将它们放在类扩展.假设你有

If you're working in Objective-C 2.0, the best way to create methods that are "hard" for others to call is to put them in a class extension. Assuming you have

@interface MyClass : NSObject {

}

- (id)aPublicMethod;

@end

MyClass.h文件中,您可以将以下内容添加到MyClass.m中:

in a MyClass.h file, you can add to your MyClass.m the following:

@interface MyClass () //note the empty category name
- (id)aPrivateMethod;
@end

@implementation MyClass
- (id)aPublicMethod {...}
- (id)aPrivateMethod {...} //extension method implemented in class implementation block
@end

类扩展的优点是扩展"方法是在原始类主体中实现的.因此,您不必担心方法实现位于哪个@implementation块中,并且如果未在类的@implementation中实现扩展方法,则编译器将发出警告.

The advanage of a class extension is that the "extension" methods are implemented in the original class body. Thus, you don't have to worry about which @implementation block a method implementation is in and the compiler will give a warning if the extension method is not implemented in the class' @implementation.

正如其他人指出的那样,Objective-C运行时不会强制执行方法的私有性(即使没有源代码也很难找出那些方法正在使用类转储),但是编译器会如果有人试图给他们打电话,则会产生警告.通常,ObjC社区会采用我告诉您不要调用此方法[[通过将其放在私有类扩展或类别中,或者仅通过记录该方法为私有]],无论如何您都已调用它无论发生什么混乱都是你的错.不要傻."对这个问题的态度.

As others have pointed out, the Objective-C runtime will not enforce the privateness of your methods (and its not too hard to find out what those methods are using class dump, even without the source code), but the compiler will generate a warning if someone tries to call them. In general, the ObjC community takes a "I told you not to call this method [by putting it in a private class extension or category or just by documenting that the method is private] and you called it anyways. Whatever mess ensues is your fault. Don't be stupid." attitude to this issue.

这篇关于是否可以在Objective-C中将方法声明为私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆