简体   繁体   English

Xcode中自定义类初始化时EXC_BAD_ACCESS code = 2错误

[英]EXC_BAD_ACCESS code=2 error on custom class initialization in Xcode

I'm attempting to initialize a custom class in my view controller to manage the data. 我正在尝试在我的视图控制器中初始化自定义类以管理数据。 Unfortunately the app crashes during the loading. 不幸的是,该应用在加载过程中崩溃了。 I'm running Xcode 5.02 with the lldb debugger. 我正在使用lldb调试器运行Xcode 5.02。 The error I get is 我得到的错误是

Thread 1: EXC_BAD_ACCESS (code=2, address=0xbf7ffffc)

The error shows up on the first line (-(void)...) of the function 错误显示在函数的第一行(-(void)...)

    -(void)setDateOfErgPiece:(NSDate *)date
{
    self.dateOfErgPiece = date;

    if(self.dateOfErgPiece) {
        // Date Formatter. So Date is displayed correctly
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateStyle:NSDateFormatterShortStyle];
        [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
        // Set value
        self.dateOfErgPieceString = [NSString stringWithFormat:@"%@", [dateFormatter stringFromDate:self.dateOfErgPiece]];
    }

}

That method is called when the object is initialized by 当对象初始化时调用该方法

-(id)initWithDate:(NSDate *)date
{
    self = [super init];

    if(self) {
        [self setDateOfErgPiece:date];
    }

    return self;
}

The (NSDate *)date value in the above init method is received from this method 从此方法接收上述init方法中的(NSDate *)date值

-(ErgNewDataEntryLogic *)ergPieceData {
    if(!_ergPieceData) _ergPieceData = [[ErgNewDataEntryLogic alloc] initWithDate:[NSDate date]];
    return _ergPieceData;
}

What is causing this error? 是什么导致此错误? If you need more information I'd be happy to provide it. 如果您需要更多信息,我们很乐意提供。 Thank you so much! 非常感谢!

I don't know if this is exactly the problem or not, but this is certainly a major problem: 我不知道这到底是不是问题,但这当然是一个主要问题:

-(void)setDateOfErgPiece:(NSDate *)date {
    self.dateOfErgPiece = date;
    // ...

self.dateOfErgPiece = date; is exactly equivalent to [self setDateOfErgPiece:date]; 完全等效于[self setDateOfErgPiece:date]; .

So, as the first line of the method, the method is calling itself. 因此,作为方法的第一行,该方法正在调用自身。 Infinite recursion. 无限递归。

This should be changed to the following... 这应该更改为以下内容...

-(void)setDateOfErgPiece:(NSDate *)date {
    _dateOfErgPiece = date;
    // ...

The other references to self.dateOfErgPiece within the method seem to be okay, because they look to be calling the getter: 方法中对self.dateOfErgPiece的其他引用似乎还可以,因为它们看起来像是在调用getter:

[self dateOfErgPiece];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM