[英]timeIntervalSinceDate gives exc_bad_access or autorelease errors
所以我有一個對象,代表在iPhone屏幕上繪制的線條。 我也有一個球在屏幕上四處移動,當球和線相交時,線就被賦予了生命。 對於我當前的版本,我不斷收到此錯誤,沒有崩潰,但是球在屏幕上停止移動:
2011-08-18 11:00:05.436 myProgram [192:5e03] * __NSAutoreleaseNoPool():類NSCFString的對象0x1531c0在沒有池的情況下自動釋放-只是泄漏
Line.h: @interface線:NSObject {
//time properties
NSTimeInterval life;
NSDate *startTime;
NSDate *currentTime;
}
//time properties
@property (nonatomic, retain) NSDate *startTime;
-(void) updateLife;
-(void) beginLifeTracking;
@end
線
@synthesize startTime;
-(void)beginLifeTracking {
[self.startTime release]; //not sure if self is necessary here but startTime is released
//in case the same string is hit again
self.startTime = [NSDate date];
startTime = [NSDate dateWithTimeIntervalSince1970:0];
//NSLog(@"Time Interval: %f",startTime);
}
-(void) updateLife {
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
}
我假設這是某種內存管理錯誤,但是我為糾正該錯誤所做的所有嘗試都失敗了。 我非常感謝您對我在這里做錯的事情的解釋。 謝謝!
當您調用[self.startTime release]
,您的釋放過度。 訪問者( setStartTime:
的工作是進行此發行。
該代碼沒有任何意義,並且很危險,因為它留下了懸掛的ivar:
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
應該是:
self.life = [[NSDate date] timeIntervalSinceDate:self.startTime];
您收到自動釋放池錯誤的事實表明您正在后台線程上運行此代碼。 您的代碼不是線程安全的,因此將是一個問題。
編輯關於線程代碼,您如何調用beginLifeTracking
? 那將是我懷疑您進入錯誤線程的地方。 我將非常關注此autoreleasepool警告。
這行:
startTime = [NSDate dateWithTimeIntervalSince1970:0];
將使用自動發布的NSDate
覆蓋實例變量startDate
。 退出該方法后,即將釋放該Mena實例並將其變為懸空指針。
這就是導致您崩潰的原因。
您的方法應該看起來像這樣:
-(void)beginLifeTracking {
self.startTime = [NSDate dateWithTimeIntervalSince1970:0];
NSLog(@"Time Interval: %@", self.startTime);
}
我還取消了對您的日志語句的注釋,並使之生效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.