简体   繁体   English

Objective-c中+和 - 方法之间的区别

[英]Difference between + and - methods in Objective-c

What is the difference between methods that are declared with - and methods that are declared with + 使用 - 声明的方法与使用+声明的方法之间有什么区别

eg 例如

- (void)methodname

+ (void)methodname

Methods prefixed with - are instance methods. -为前缀的方法是实例方法。 This means they can only be invoked on an instance of a class, eg: 这意味着它们只能在类的实例上调用,例如:

[myStringInstance length];

Methods prefixed with + are class methods. 前缀为+的方法是类方法。 This means they can be called on Classes, without needing an instance, eg: 这意味着它们可以在类上调用,而不需要实例,例如:

[NSString stringWithString:@"Hello World"];

minus are instance methods (only accessible via an instantiated object) 减去实例方法(只能通过实例化对象访问)

plus are class methods (like in Java Math.abs(), you can use it without an instantited object) 加上类方法(比如Java Math.abs(),你可以在没有即时对象的情况下使用它)

+(void)methodname is a class variable and -(void)methodname is object variable. +(void)methodname是一个类变量, -(void)methodname是对象变量。

Lets say you make a utility class that has a method to reverse string. 假设您创建了一个具有反向字符串方法的实用程序类。 The class you call MYUtility. 你称之为MYUtility的课程。

If you use +, like 如果你使用+,就像

+ (NSString *)reverse:(NSString *)stringToReverse

You could use it directly like 你可以直接使用它

NSString *reversed = [MYUtility stringToReverse:@"I Love objective C"];

if you used a -, like 如果你使用 - ,喜欢

- (NSString *)reverse:(NSString *)stringToReverse

You have to use : 你必须使用:

MYUtility *myUtil = [[MYUtility alloc] init];
NSString *reversed = [myUtil stringToReverse:@"There are many ways to do the same thing"];

With the class based function, you just call directly, but you don't have access to any local variables besides #defines that you can do because the class isn't instantiated. 使用基于类的函数,您只需直接调用,但除了#defines之外,您无法访问除了#defines之外的任何局部变量,因为该类未实例化。

But with the - (NSString you must instantiate the class before use, and you have access to all local variables. 但是使用 - (NSString,您必须在使用之前实例化该类,并且您可以访问所有本地变量。

This isn't a pick one thing and stay with it, many classes have both, just look at the header file for NSString, it is littered with + functions and - functions. 这不是一个选择并坚持下去,许多类都有,只要查看NSString的头文件,它就会散落着+函数和 - 函数。

According to this page : 根据这个页面

Instance methods begin with - and class level methods begin with + 实例方法以 - 开头,类级方法以+开头

See this SO question for more information. 有关更多信息,请参阅此SO问题

The first is an instance method and the second is a class method. 第一个是实例方法,第二个是类方法。 You should read Apple's Objective-C documentation to learn about the difference. 您应该阅读Apple的Objective-C文档以了解其中的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM