1

I'm new to ios programming. I've read through the Apple developer memory guide and ARC guide, and I thought I already understood the memory management, but in fact I didn't.

Please help me identify where's wrong and why it's wrong, thanks.

First of all, the whole program, if I'm not wrong, is ARC enabled.

    NSDate *expireDate = nil;
    //using debug, expiresIn = 86400
    id expiresIn = [responseObject valueForKey:@"expires_in"];
    if (expiresIn != nil && ![expiresIn isEqual:[NSNull null]]) {
        //using debug, expireDate = currentDate + 1day
        expireDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn doubleValue]];
    }
    [credential setExpiration:expireDate];

and see setExpiration implementation in credential,

@property (readwrite, nonatomic) NSDate *expiration;
- (void)setExpiration:(NSDate *)expireDate
{
    //using debug, expireDate = currentDate + 1day
    if (!expireDate) {
        return;
    }
    // oops, the following line, caused exc_bad_access 
    //  (code = 2, address=0xxxxxxx)
    // and after the exception occurs, expireDate = nil in debug window
    self.expiration = expireDate;
}

The error is that, the self.expiration = expireDate causes memory access failure exception (exc_bad_access), which make me confused. Will expireDate be freed somewhere in between the if(!expireDate) and self.expiration=expireDate?

I don't really understand why this happens, please help.

Thanks again.

===========

Thanks for the answer,

I changed to _expiration = expireDate, then the exception is gone.

However, why the following for NSString works (without exception), but the NSDate * doesn't?

@property (readwrite, nonatomic) NSString *refreshToken;
- (void)setRefreshToken:(NSString *)refreshToken
{
    if (!refreshToken) {
        return;
    }

    self.refreshToken = refreshToken;
}
4

3 回答 3

3

self.expiration = expireDate;应该是_expiration = expireDate;

您收到错误是因为self.expiration = expireDate;设置了一个无限递归调用setExpiration,导致堆栈溢出。

于 2013-10-24T09:13:29.570 回答
1

循环保留self.expiration = expireDate;

- (void)setExpiration:(NSDate *)expireDate
{
    expiration = expireDate;
}
于 2013-10-24T09:14:18.093 回答
0

喜欢这个 .h 文件

@property (readwrite, nonatomic) NSDate *expiration;

.m 文件

@synthesize  expiration = _expiration;

- (void)setExpiration:(NSDate *)expireDate
{
    //using debug, expireDate = currentDate + 1day
    if (!expireDate) {
        return;
    }

    self.expiration = expireDate;
}
于 2013-10-24T09:22:42.307 回答