繁体   English   中英

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

[英]What is the difference between + and - when defining a property of method?

在属性和方法的声明前面的-和+号令我非常困惑。 如果以这种方式声明该方法,会有什么区别:

- (void)methodName:(id)sender {}

这样

+ (void)methodName:(id)sender {}

我真的不明白。

“ +”方法是类方法,可以直接在元类上调用。 因此,它无权访问实例变量。

“-”方法是一个实例方法,可以完全访问该类的相关实例。

例如

@interface SomeClass

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

@property (nonatomic, assign) int someProperty;

@end

随后,您可以执行:

[SomeClass classMethod]; // called directly on the metaclass

要么:

SomeClass *someInstance = etc;

[someInstance instanceMethod]; // called on an instance of the class

注意:

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

为了体现@Tommy的答案,(-)方法将使用“ self”变量,该变量是该方法将使用的类实例。 (+)方法不会有。

例如,如果您有一个FooBar类,并且想要比较两个实例,则可以执行以下任一操作:

+ (BOOL) compare:(FooBar)fb1 and:(FooBar)fb2 {
        // compare fb1 and fb2
        // return YES or NO
}

要么

- (BOOL) compare:(FooBar)fb2
        // compare self and fb2
        // return YES or NO
}

第二个例程的“自我”变量与第一个例程的fb1相似。 (这些例程是人为设计的,但希望您能理解。)

- (void)methodName:(id)sender {}

是实例方法,表示您创建类的实例,并且可以在对象上调用该方法,或者以Objective-C的说法将消息发送给对象选择器。

+ (void)methodName:(id)sender {}

是一个类方法,意味着它是您在类本身上调用的静态方法,而无需首先实例化一个对象。

在下面的示例中, allocstringWithString是类方法,您可以直接在NSString类上调用它,而无需对象。 另一方面, initWithString是一个实例方法,您可以对[NSString alloc]返回的对象进行调用。

NSString* test = [[NSString alloc] initWithString:@"test"];

NSString* test2 = [NSString stringWithString:@"test2"];

暂无
暂无

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

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