EXC_BAD_ACCESS 崩溃:self.x 与 _x
下面的代码不会
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
_heading = newHeading.trueHeading;
NSLog(@"heading - %.2f", newHeading.trueHeading);
//NSLog(@"Updating heading - %f", newHeading.trueHeading);
}
像这个那样
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
self.heading = newHeading.trueHeading;
NSLog(@"heading - %.2f", newHeading.trueHeading);
//NSLog(@"Updating heading - %f", newHeading.trueHeading);
}
崩溃有人可以解释为什么会出现这种情况吗?该属性看起来像:
@property (nonatomic, assign) float heading;
而且它永远不会在 init 方法中初始化,因为我不想存储一个值,直到它正确为止。现在是:
- (id) initUser
{
return [self init];
}
The following code does not crash
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
_heading = newHeading.trueHeading;
NSLog(@"heading - %.2f", newHeading.trueHeading);
//NSLog(@"Updating heading - %f", newHeading.trueHeading);
}
where as this one does
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
self.heading = newHeading.trueHeading;
NSLog(@"heading - %.2f", newHeading.trueHeading);
//NSLog(@"Updating heading - %f", newHeading.trueHeading);
}
Can someone explain why this is the case? The property looks like:
@property (nonatomic, assign) float heading;
Also it is never initialized in the init method because I don't want to store a value until it is right. Right now it is:
- (id) initUser
{
return [self init];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
声明属性后,应使用 @synthesize 告诉编译器生成 getter 和 setter 方法。默认情况下,这些方法被命名为 foo 和 setFoo,其中 foo 是变量的名称。另外,默认情况下,属性表示的变量与属性具有相同的名称,除非您使用 @synthesize foo=_foo 更改此名称以使用不同的命名实例变量。
After you declare a property, you should use
@synthesize
to tell the compiler to generate a getter and setter method. By default, these methods are named foo and setFoo, where foo is a name of the variable. Also, by default, the variable represented by the property has the same name as a property, unless you change this with @synthesize foo=_foo to use to a different named instance variable.