在定义方法的属性时,+和 - 之间有什么区别?

cod*_*nja 1 macos cocoa objective-c ios

财产和方法声明面前的 - 和+标志让我很困惑.如果我以这种方式声明方法,是否有区别:

- (void)methodName:(id)sender {}
Run Code Online (Sandbox Code Playgroud)

就这样

+ (void)methodName:(id)sender {}
Run Code Online (Sandbox Code Playgroud)

我真的不明白.

Tom*_*mmy 6

'+'方法是一种类方法,可以直接在元类上调用.因此它无法访问实例变量.

' - '方法是一种实例方法,可以完全访问类的相关实例.

例如

@interface SomeClass

+ (void)classMethod;
- (void)instanceMethod;

@property (nonatomic, assign) int someProperty;

@end
Run Code Online (Sandbox Code Playgroud)

您随后可以执行:

[SomeClass classMethod]; // called directly on the metaclass
Run Code Online (Sandbox Code Playgroud)

要么:

SomeClass *someInstance = etc;

[someInstance instanceMethod]; // called on an instance of the class
Run Code Online (Sandbox Code Playgroud)

注意:

+ (void)classMethod
{
    NSLog(@"%d", self.someProperty); // this is impossible; someProperty belongs to
                                     // instances of the class and this is a class
                                     // method
}
Run Code Online (Sandbox Code Playgroud)