[英]In Objective-C what is the difference between defining something (say a property) in the header file as opposed to the .m file?
[英]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 {}
是一個類方法,意味着它是您在類本身上調用的靜態方法,而無需首先實例化一個對象。
在下面的示例中, alloc
和stringWithString
是類方法,您可以直接在NSString
類上調用它,而無需對象。 另一方面, initWithString
是一個實例方法,您可以對[NSString alloc]
返回的對象進行調用。
NSString* test = [[NSString alloc] initWithString:@"test"];
NSString* test2 = [NSString stringWithString:@"test2"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.