[英]What is the difference between + and - when defining a property of method?
and the - and + signs in front of a declaration of property and method confuses me a lot. 在属性和方法的声明前面的-和+号令我非常困惑。 Is there a difference if I declare the method this way: 如果以这种方式声明该方法,会有什么区别:
- (void)methodName:(id)sender {}
and this way 这样
+ (void)methodName:(id)sender {}
I really don't get it. 我真的不明白。
A '+' method is a class method, and can be called directly on the metaclass. “ +”方法是类方法,可以直接在元类上调用。 It therefore has no access to instance variables. 因此,它无权访问实例变量。
A '-' method is an instance method, with full access to the relevant instance of the class. “-”方法是一个实例方法,可以完全访问该类的相关实例。
Eg 例如
@interface SomeClass
+ (void)classMethod;
- (void)instanceMethod;
@property (nonatomic, assign) int someProperty;
@end
You can subsequently perform: 随后,您可以执行:
[SomeClass classMethod]; // called directly on the metaclass
Or: 要么:
SomeClass *someInstance = etc;
[someInstance instanceMethod]; // called on an instance of the class
Note that: 注意:
+ (void)classMethod
{
NSLog(@"%d", self.someProperty); // this is impossible; someProperty belongs to
// instances of the class and this is a class
// method
}
To embelish on @Tommy's answer, the (-)methods will have the use of a 'self' variable which is the class instance that the method will work on. 为了体现@Tommy的答案,(-)方法将使用“ self”变量,该变量是该方法将使用的类实例。 The (+) methods won't have that. (+)方法不会有。
For example, if you had a class FooBar and you wanted to compare 2 instances, you could do either of the following: 例如,如果您有一个FooBar类,并且想要比较两个实例,则可以执行以下任一操作:
+ (BOOL) compare:(FooBar)fb1 and:(FooBar)fb2 {
// compare fb1 and fb2
// return YES or NO
}
or 要么
- (BOOL) compare:(FooBar)fb2
// compare self and fb2
// return YES or NO
}
The second routine has the 'self' variable which is similar to the fb1 in the first routine. 第二个例程的“自我”变量与第一个例程的fb1相似。 (These routines are contrived, but I hope you get the picture.) (这些例程是人为设计的,但希望您能理解。)
- (void)methodName:(id)sender {}
is an instance method, meaning you create an instance of a class, and can call the method on the object, or in Objective-C parlance, send a message to the object selector. 是实例方法,表示您创建类的实例,并且可以在对象上调用该方法,或者以Objective-C的说法将消息发送给对象选择器。
+ (void)methodName:(id)sender {}
is a class method, meaning it is a static method you call on the class itself, without first instantiating an object. 是一个类方法,意味着它是您在类本身上调用的静态方法,而无需首先实例化一个对象。
In the following example, alloc
and stringWithString
are class methods, which you call on the NSString
class directly, no object required. 在下面的示例中, alloc
和stringWithString
是类方法,您可以直接在NSString
类上调用它,而无需对象。 On the other hand, initWithString
is an instance method, which you call on the object returned by [NSString alloc]
. 另一方面, initWithString
是一个实例方法,您可以对[NSString alloc]
返回的对象进行调用。
NSString* test = [[NSString alloc] initWithString:@"test"];
NSString* test2 = [NSString stringWithString:@"test2"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.