What's the difference between _variable & self.variable in Objective-C? [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-17 19:28:37

问题


I am quite new to Objective C and iOS, currently trying to learn app development using the iOS 6 SDK. One concept I really can't wrap my head around is the difference between "_variable" and "self.variable" when being accessed in the .m file. Are they the same? Or different?

Following is a simple sample

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

So is there a difference in the above implementations to set a variable? Variable "myName" is Public while "anotherName" is Private.

Would greatly appreciate any inputs. Thanks!


回答1:


The difference is that:

the variable names with _ are instance variables.

self.variable is calling a getter method on your object.

In your example, the instance variables are automatically generated and you don't need to synthesize your properties either.

The real important difference in your example comes into play if you are not using ARC-

self.variable will retain an object for you if you mark the property with retain or strong _variable does not address memory management at all



来源:https://stackoverflow.com/questions/15129795/whats-the-difference-between-variable-self-variable-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!