我在一些iPhone示例中看到,属性在变量前面使用了下划线_.有谁知道这意味着什么?或者它是如何工作的?
我正在使用的接口文件如下所示:
@interface MissionCell : UITableViewCell {
Mission *_mission;
UILabel *_missionName;
}
@property (nonatomic, retain) UILabel *missionName;
- (Mission *)mission;
Run Code Online (Sandbox Code Playgroud)
我不确定上面做了什么,但是当我尝试设置任务名称时:
aMission.missionName = missionName;
Run Code Online (Sandbox Code Playgroud)
我收到错误:
请求成员'missionName'的东西不是结构或联合
注意:对于那些试图理解这一点的人来说,我想出了我的困惑的根源.在.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中使用下划线前缀属性名称
我刚刚开始iphone App开发并注意到当你生成一个新项目时,可以在AppDelegate.m中看到以下代码
@synthesize window = _window;
@synthesize viewController = _viewController;
Run Code Online (Sandbox Code Playgroud)
它说,在AppDelegate.h文件中
@property (strong, nonatomic) UIWindow window;
@property (strong, nonatomic) ViewController controller;
Run Code Online (Sandbox Code Playgroud)
我想知道究竟是什么意思,特别是合成部分.它是否实例化了一个本地私有变量?如果是这样,这与说@synthesize viewController有什么不同;
谢谢
所以我发现在合成属性时你必须使用下划线,这对我来说没有任何意义.
那么,让我们开始吧.在我们的.h文件中,我们写了这一行:
@property (nonatomic) double speed;
Run Code Online (Sandbox Code Playgroud)
在我们的.m文件中,我们这样做:
@synthesize speed = _speed;
Run Code Online (Sandbox Code Playgroud)
为什么?据我所知,property生成一个实例变量并为它创建setter和getter.但到底是怎么回事
@synthesize speed = _speed
Run Code Online (Sandbox Code Playgroud)
做?常识告诉我,我们将_speed中的值赋予速度.好的.我们在哪里宣布_speed?为什么编译器没有给我们错误?它应该是什么意思?为什么这样混淆代码?
我的问题在这里:
如果我这样做会发生什么
@synthesize speed;
Run Code Online (Sandbox Code Playgroud)
没有_speed,我会得到错误或一些错误吗?这种语法后的原因是什么?制作时他们在想什么?_speed来自哪里?它是什么?它是指针还是真正的价值?到底是怎么回事?
好吧,以前一定要问这个但是我看起来很生气,一无所获:
我在我的iphone应用程序中有一个简单的数组,我这样定义:
@property (nonatomic, strong) NSArray *pages;
@synthesize pages = _pages;
Run Code Online (Sandbox Code Playgroud)
我在Apples示例代码中看到了这一点,并且认为这是编写self.pages(即_pages替换self.pages)的一个很好的捷径,如下所示:
_pages = [[NSArray alloc] init];
Run Code Online (Sandbox Code Playgroud)
但是Apple再次拥有它(不完全像这样,但看起来好像他们一直随机交换):
self.pages = [NSKeyedUnarchiver unarchiveObjectWithData:contents];
Run Code Online (Sandbox Code Playgroud)
最后:
[_pages release];
Run Code Online (Sandbox Code Playgroud)
这完全让我感到困惑._pages和self.pages之间会有什么区别?
谢谢你的帮助.
objective-c ×5
ios ×2
iphone ×2
cocoa ×1
cocoa-touch ×1
self ×1
syntax ×1
synthesize ×1
variables ×1
xcode ×1