在 Objective-C 中为类定义私有方法的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/172598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to define private methods for a class in Objective-C
提问by Yurii Soldak
I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.
我刚开始编写 Objective-C 并且有 Java 背景,想知道编写 Objective-C 程序的人是如何处理私有方法的。
I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C.
我知道可能有几种约定和习惯,并将这个问题视为人们在处理 Objective-C 中的私有方法时使用的最佳技术的聚合器。
Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?
请在发布时为您的方法提供一个论据。为什么好?它有哪些(您知道的)缺点以及您如何处理它们?
As for my findings so far.
至于我目前的发现。
It is possible to use categories[e.g. MyClass (Private)] defined in MyClass.m file to group private methods.
可以使用在 MyClass.m 文件中定义的类别[例如 MyClass (Private)] 来对私有方法进行分组。
This approach has 2 issues:
这种方法有两个问题:
- Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block
- You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo".
- Xcode(和编译器?)不会检查您是否在相应的 @implementation 块中定义了私有类别中的所有方法
- 您必须将@interface 声明您的私有类别放在 MyClass.m 文件的开头,否则 Xcode 会抱怨诸如“self 可能不会响应消息“privateFoo”之类的消息。
The first issue can be worked around with empty category[e.g. MyClass ()].
The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.
第一个问题可以用空类别解决[例如 MyClass ()]。
第二个让我很困扰。我希望在文件末尾附近实现(和定义)私有方法;我不知道这是否可能。
回答by Alex
There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClassas the public methods. So I structure my classes like this:
正如其他人已经说过的那样,Objective-C 中没有私有方法这样的东西。但是,从 Objective-C 2.0(即 Mac OS X Leopard、iPhone OS 2.0 及更高版本)开始,您可以创建一个@interface MyClass ()名为Class Extension的空名称(即)类别。类扩展的独特之处在于方法实现必须@implementation MyClass与公共方法相同。所以我这样构造我的类:
In the .h file:
在 .h 文件中:
@interface MyClass {
// My Instance Variables
}
- (void)myPublicMethod;
@end
And in the .m file:
在 .m 文件中:
@interface MyClass()
- (void)myPrivateMethod;
@end
@implementation MyClass
- (void)myPublicMethod {
// Implementation goes here
}
- (void)myPrivateMethod {
// Implementation goes here
}
@end
I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.
我认为这种方法的最大优点是它允许您按功能而不是(有时是任意的)公共/私有区别对方法实现进行分组。
回答by Yurii Soldak
There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interfaceat the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods)can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-).
Objective-C 中并没有真正的“私有方法”,如果运行时可以确定要使用哪个实现,它就会这样做。但这并不是说没有不属于文档化接口一部分的方法。对于这些方法,我认为一个类别很好。我不会@interface像第 2 点那样将 放在 .m 文件的顶部,而是将其放入自己的 .h 文件中。我遵循的一个约定(并且在其他地方看到过,我认为这是 Apple 约定,因为 Xcode 现在自动支持它)是在它的类和类别之后命名这样的文件,用 + 分隔它们,所以@interface GLObject (PrivateMethods)可以在GLObject+PrivateMethods.h. 提供头文件的原因是您可以将其导入单元测试类:-)。
By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:
顺便说一下,就 .m 文件末尾附近的实现/定义方法而言,您可以通过在 .m 文件底部实现类别来使用类别来实现:
@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end
or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.
或者使用类扩展(您称之为“空类别”的东西),只需最后定义这些方法。Objective-C 方法可以在实现中以任何顺序定义和使用,因此没有什么可以阻止您将“私有”方法放在文件末尾。
Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility.
即使使用类扩展,我也会经常创建一个单独的标头 ( GLObject+Extension.h),以便我可以在需要时使用这些方法,模仿“朋友”或“受保护”的可见性。
Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.
由于这个答案最初是写的,clang 编译器已经开始为 Objective-C 方法做两遍。这意味着您可以避免完全声明您的“私有”方法,无论它们是在调用站点之上还是之下,编译器都会找到它们。
回答by Andy
While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.
虽然我不是 Objective-C 专家,但我个人只是在我的类的实现中定义方法。当然,它必须在调用它的任何方法之前(在上面)定义,但它肯定需要最少的工作来完成。
回答by justin
Defining your private methods in the @implementationblock is ideal for most purposes. Clang will see these within the @implementation, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.
在@implementation块中定义私有方法对于大多数用途来说都是理想的。@implementation无论声明顺序如何,Clang 都会在 中看到这些。无需在类延续(又名类扩展)或命名类别中声明它们。
In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation).
在某些情况下,您需要在类延续中声明方法(例如,如果在类延续和 之间使用选择器@implementation)。
staticfunctions are very good for particularly sensitive or speed critical private methods.
static函数非常适合特别敏感或速度关键的私有方法。
A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).
命名前缀的约定可以帮助您避免意外覆盖私有方法(我发现类名作为前缀安全)。
Named categories (e.g. @interface MONObject (PrivateStuff)) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:
@interface MONObject (PrivateStuff)由于加载时潜在的命名冲突,命名类别(例如)并不是一个特别好的主意。它们真的只对友元或受保护的方法有用(这很少是一个好的选择)。为了确保您收到不完整的类别实现的警告,您应该实际实现它:
@implementation MONObject (PrivateStuff)
...HERE...
@end
Here's a little annotated cheat sheet:
这是一个带注释的小抄:
MONObject.h
MONObject.h
@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
MONObject.m
MONObject.m
@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
Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.
另一种可能不太明显的方法:C++ 类型既可以非常快,又可以提供更高程度的控制,同时最大限度地减少导出和加载的 objc 方法的数量。
回答by dreamlax
You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables.
您可以尝试在您的实现下方或上方定义一个静态函数,该函数采用指向您的实例的指针。它将能够访问您的任何实例变量。
//.h file
@interface MyClass : Object
{
int test;
}
- (void) someMethod: anArg;
@end
//.m file
@implementation MyClass
static void somePrivateMethod (MyClass *myClass, id anArg)
{
fprintf (stderr, "MyClass (%d) was passed %p", myClass->test, anArg);
}
- (void) someMethod: (id) anArg
{
somePrivateMethod (self, anArg);
}
@end
回答by FellowMD
You could use blocks?
你可以用块吗?
@implementation MyClass
id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};
NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
{
return a + b;
};
//public methods, etc.
- (NSObject) thePublicOne
{
return createTheObject();
}
@end
I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.
我知道这是一个老问题,但这是我在寻找这个问题的答案时发现的第一个问题。我还没有在其他地方看到过这个解决方案的讨论,所以如果这样做有什么愚蠢的地方,请告诉我。
回答by Zack Sheppard
every objects in Objective C conform to NSObject protocol, which holds onto the performSelector:method. I was also previously looking for a way to create some "helper or private" methods that I did not need exposed on a public level. If you want to create a private method with no overhead and not having to define it in your header file then give this a shot...
Objective C 中的每个对象都符合 NSObject 协议,该协议持有performSelector:方法。我之前也在寻找一种方法来创建一些我不需要在公共级别公开的“帮助程序或私有”方法。如果您想创建一个没有开销的私有方法并且不必在头文件中定义它,那么请试一试......
define the your method with a similar signature as the code below...
使用与以下代码类似的签名定义您的方法...
-(void)myHelperMethod: (id) sender{
// code here...
}
then when you need to reference the method simply call it as a selector...
然后当您需要引用该方法时,只需将其作为选择器调用...
[self performSelector:@selector(myHelperMethod:)];
this line of code will invoke the method you created and not have an annoying warning about not having it defined in the header file.
这行代码将调用您创建的方法,并且不会出现有关未在头文件中定义它的烦人警告。
回答by rebelzach
If you wanted to avoid the @interfaceblock at the top you could always put the private declarations in another file MyClassPrivate.hnot ideal but its not cluttering up the implementation.
如果你想避免@interface顶部的块,你总是可以将私有声明放在另一个MyClassPrivate.h不理想的文件中,但它不会使实现变得混乱。
MyClass.h
我的类.h
interface MyClass : NSObject {
@private
BOOL publicIvar_;
BOOL privateIvar_;
}
@property (nonatomic, assign) BOOL publicIvar;
//any other public methods. etc
@end
MyClassPrivate.h
MyClassPrivate.h
@interface MyClass ()
@property (nonatomic, assign) BOOL privateIvar;
//any other private methods etc.
@end
MyClass.m
我的课堂.m
#import "MyClass.h"
#import "MyClassPrivate.h"
@implementation MyClass
@synthesize privateIvar = privateIvar_;
@synthesize publicIvar = publicIvar_;
@end
回答by Rich Schonthal
One more thing that I haven't seen mentioned here - Xcode supports .h files with "_private" in the name. Let's say you have a class MyClass - you have MyClass.m and MyClass.h and now you can also have MyClass_private.h. Xcode will recognize this and include it in the list of "Counterparts" in the Assistant Editor.
我还没有在这里提到的另一件事 - Xcode 支持名称中带有“_private”的 .h 文件。假设你有一个 MyClass 类——你有 MyClass.m 和 MyClass.h,现在你也可以有 MyClass_private.h。Xcode 将识别这一点并将其包含在“助理编辑器”的“对应物”列表中。
//MyClass.m
#import "MyClass.h"
#import "MyClass_private.h"
回答by Sneg
There is a benefit of private methods absence. You can move the logic that you intended to hide to the separate class and use it as delegate. In this case you can mark delegate object as private and it will not be visible from outside. Moving logic to the separate class (maybe several) makes better design of your project. Cause your classes become simpler and your methods are grouped in classes with proper names.
没有私有方法有一个好处。您可以将要隐藏的逻辑移到单独的类中并将其用作委托。在这种情况下,您可以将委托对象标记为私有,并且从外部看不到它。将逻辑移到单独的类(可能有几个)可以更好地设计您的项目。因为你的类变得更简单,你的方法被分组到具有适当名称的类中。

