_variable&的区别是什么? Objective.C中的self.variable? [英] What's the difference between _variable & self.variable in Objective-C?
问题描述
我对Objective C和iOS很陌生,目前正在尝试使用iOS 6 SDK学习应用程序开发。我真的无法理解的一个概念是在.m文件中访问时_variable和self.variable之间的区别。它们是一样的吗?或者不同?
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?
以下是一个简单的样本
MyClass.h
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (strong, nonatomic) NSString *myName;
@end
MyClass.m
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是私有的。
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!
推荐答案
区别在于:
变量名称 _
是实例变量。
the variable names with _
are instance variables.
self.variable
正在对象上调用getter方法。
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.
您的示例中真正重要的区别在于如果你没有使用ARC,那就进入游戏 -
The real important difference in your example comes into play if you are not using ARC-
self.variable
如果你标记的话,将为你保留一个对象属性保留
或 strong
_variable
根本不解决内存管理问题
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
这篇关于_variable&的区别是什么? Objective.C中的self.variable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!