注意:对于那些试图理解这一点的人来说,我想出了我的困惑的根源.在.h,我有:
...
@interface myClass : parentClass {
className *variableName:
}
@property (strong, nonatomic) className *variableName;
...
Run Code Online (Sandbox Code Playgroud)
这导致self.variableName和_variableName是.m中的两个不同变量.我需要的是:
...
@interface myClass : parentClass {
className *_variableName:
}
@property (strong, nonatomic) className *variableName;
...
Run Code Online (Sandbox Code Playgroud)
然后,在类'.m中,self.variableName和_variableName是等价的
在全新的Xcode的4.5+,与ARC,针对iOS 5.0及项目,有一个明显的优势(运行时的效率,速度等)使用_variableName了self.variableName与旧式@synthesize variableName?
我的理解是Xcode 4.5+将创建一个_variableName相当于的默认访问器,self.variableName并且唯一不使用的原因@synthesize variableName是为了避免iVars和传入变量之间的混淆,对吗?
对我来说,只是使用self.variableName访问iVar似乎是最直接和明确的,你正在寻找哪个变量.除了打字_与self.,使用是否有优势_variableName?
我是Objective C和iOS的新手,目前正在尝试使用iOS 6 SDK学习应用程序开发.我真的无法理解的一个概念是在.m文件中访问时"_variable"和"self.variable"之间的区别.它们是一样的吗?还是不同?
以下是一个简单的示例
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (strong, nonatomic) NSString *myName;
@end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
那么上面的实现设置变量有什么不同吗?变量"myName"是Public,而"anotherName"是Private.
非常感谢任何投入.谢谢!