Objective-C 静态/类方法定义 - “静态”和“静态”之间有什么区别?和“”?
我想知道是否有人可以解释以下功能之间的区别。它们都是静态的,但需要不同的签名语法。我想知道这些在运行时是如何处理的,为什么你会使用其中一个而不是另一个?
+ (int) returnInt:(NSString *)myString1 withString2:(NSString *)myString2
{
if ([myString1 isEqualToString:myString2])
return 1;
else
return 0;
}
对比
static int returnInt(NSString *myString1, NSString *myString2)
{
if ([myString1 isEqualToString:myString2])
return 1;
else
return 0;
}
谢谢!
I'm wondering if someone can explain the difference between the functions below. They are both static, but require different signature syntaxes. I'm wondering how these are handled at runtime, and why you would use one over the other?
+ (int) returnInt:(NSString *)myString1 withString2:(NSString *)myString2
{
if ([myString1 isEqualToString:myString2])
return 1;
else
return 0;
}
vs.
static int returnInt(NSString *myString1, NSString *myString2)
{
if ([myString1 isEqualToString:myString2])
return 1;
else
return 0;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与(例如)C++ 中的静态成员函数只是类命名空间中的普通函数不同,Objective-C 具有适当的类方法。
由于类是对象,因此调用类方法实际上就像调用类上的实例方法一样。这样做的主要后果是:
1) 调用类方法会产生轻微的(尽管通常无关紧要的)开销,因为方法调用是在运行时解析的。
2) 类方法有一个隐式的“self”参数,就像实例方法一样。在他们的例子中,“self”是指向类对象的指针。
3)类方法被子类继承。
2 和 3 一起意味着您可以使用类方法执行类似的操作:
然后创建一个继承该方法的新类并返回其自身的新实例,而不是超类。
我相信将普通的 c 函数标记为 static 只会使其对定义它的文件之外的文件不可用。如果您想创建一个仅与一个类相关的辅助函数并且您想避免,那么您通常会这样做污染全局命名空间。
Unlike in (say) C++, where static member functions are just ordinary functions in the class' namespace, Objective-C has proper class methods.
Since classes are objects, calling a class method is really like calling an instance method on the class. The main consequences of this are:
1) Calling a class method incurs a slight (although generally inconsequential) overhead, since method calls are resolved at runtime.
2) Class methods have an implicit 'self' argument, just like instance methods. In their case, 'self' is a pointer to the class object.
3) Class methods are inherited by subclasses.
together, 2 and 3 mean that you can do stuff like this with a class method:
then create a new class that inherits the method and returns a new instance of itself, rather than the superclass.
I believe that marking an ordinary c function static will just make it unavailable to files other than the one it's defined in. You'd generally do this if you wanted to make a helper function that is only relevant to one class and you wanted to avoid polluting the global namespace.