我對Objective C和iOS非常陌生,目前正嘗試使用iOS 6 SDK學習應用程序開發。當我在.m文件中訪問時,我實際上無法包裹頭的一個概念是「_variable」和「self.variable」之間的區別。他們是一樣的嗎?還是不同?Objective-C中_variable和self.variable有什麼區別?
下面是一個簡單的示例
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (strong, nonatomic) NSString *myName;
@end
MyClass.m
#import "MyClass.h"
@interface MyClass()
@property (nonatomic, strong) NSString *anotherName;
@end
@implementation MyClass
- (void) myFunction {
_myName = @"Ares";
self.myName = @"Ares";
_anotherName = @"Michael";
self.anotherName = @"Michael";
}
@end
那麼,有在上述實施方式中的差來設置一個變量? 變量「myName」是公開的,而「anotherName」是私人的。
將不勝感激任何投入。謝謝!
[self.ivar和ivar之間的區別?](http://stackoverflow.com/q/4142177/),[自我和正常變量之間的區別](http://stackoverflow.com/q/ 536388 /),[Properties and accessors](http://stackoverflow.com/q/6085080/),[Ivar property,access via self?](http://stackoverflow.com/q/4088801/), [何時訪問屬性](http://stackoverflow.com/q/4271657/),[使用合成獲取器時,「self.foo」和「foo」之間的(風格)區別是什麼?](http: //更多](http://stackoverflow.com/search?q=%5Bobjc%5D+self.ivar) – 2013-02-28 07:40:16
其實這個問題不是重複的。作爲初學者,我尋找了_variable和self.variable之間的區別。我會忽略那些不使用下劃線的問題,所以這是我唯一的問題。但是,@Josh,你的評論無論如何幫助我,理解他們是同樣的事情。 – Arjan 2014-02-20 09:18:40
下劃線不會輕微改變ivars的性質或功能:[Cocoa/ObjC類中的變量前的下劃線如何工作?](http://stackoverflow.com/q/822487) – 2014-02-20 19:22:58