EXC_BAD_ACCESS 使用保留属性?
我的类中有一个名为 location 的属性,它使用非原子保留属性。但是,当我第一次将其分配给某些东西时,我收到 EXC_BAD_ACCESS 错误。它在下面代码中的赋值时崩溃:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(!self.location)
{
self.location =
[[Point2D alloc] initWithX:newLocation.coordinate.longitude Y:newLocation.coordinate.latitude];
}
据我记得,当您使用保留属性时,它会自动释放当前对象并在合成新对象时保留新对象。我认为它抛出这个错误是因为我正在释放一些不存在的东西。但有没有办法解决这个问题,还是我认为这一切都是错误的?另外,当我使用变量本身时,它不会抛出错误,只有当 self.被使用。
这也是我的 Point2D 类信息:
@interface Point2D : NSObject {
}
@property (nonatomic, assign) float x, y;
-(id)initWithX:(float)nx Y:(float)ny;
@end
@implementation Point2D
@synthesize x = _x, y = _y;
-(id)init
{
return [self initWithX:0.00 Y:0.00];
}
-(id)initWithX:(float)nx Y:(float)ny
{
self = [super init];
self.x = nx;
self.y = ny;
NSLog(@"initWithX");
return self;
}
@end
I have a property in my class called location that uses the nonatomic, retain property. However, I am getting an EXC_BAD_ACCESS error when I assign it to something for the first time. It crashes on the assignment in the code below:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(!self.location)
{
self.location =
[[Point2D alloc] initWithX:newLocation.coordinate.longitude Y:newLocation.coordinate.latitude];
}
From what I remember when you use a retain property it automatically releases the current object and retains the new object when you synthesize it. I am thinking that it is throwing this error because I am releasing something that isn't there. But is there a way to get around that or am I seeing it all wrong? Also, it does not throw an error when I use the variable itself, only when self. is used.
Here is my Point2D class information also:
@interface Point2D : NSObject {
}
@property (nonatomic, assign) float x, y;
-(id)initWithX:(float)nx Y:(float)ny;
@end
@implementation Point2D
@synthesize x = _x, y = _y;
-(id)init
{
return [self initWithX:0.00 Y:0.00];
}
-(id)initWithX:(float)nx Y:(float)ny
{
self = [super init];
self.x = nx;
self.y = ny;
NSLog(@"initWithX");
return self;
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查 newLocation 以确保其引用和/或其坐标属性未返回空引用。
Check newLocation to make sure that its reference and/or its coordinate property are not returning a null reference.
你综合了这个属性吗?我建议你先检查一下。如果你在 if(!self.location) 部分出现错误,你可以用调试器检查一下吗?
self.location = [[Point2D alloc] initWithX...... 部分?
Have you synthesized the property?I suggest you check that first.And can you check with the debugger if you get the error on if(!self.location) part or
self.location = [[Point2D alloc] initWithX...... part?