2011-08-18 54 views
0

所以我有一個對象,它代表在iPhone屏幕上繪製的一條線。我還有一個在屏幕上移動的球,當球和線交叉時,繩子就有了生命。對於我目前的積累,我收到此錯誤不斷,有沒有崩潰,但是球停在屏幕上移動:timeIntervalSinceDate給出exc_bad_access或autorelease錯誤

2011-08-18 11:00:05.436 myProgram [192:5e03] * __NSAutoreleaseNoPool() :對象0x1531c0類NSCFString自動釋放與地方沒有游泳池 - 剛剛泄露

Line.h: @interface行:NSObject的{

//time properties 
NSTimeInterval life; 
NSDate *startTime; 
NSDate *currentTime; 
} 



//time properties 
@property (nonatomic, retain) NSDate *startTime; 


-(void) updateLife; 

-(void) beginLifeTracking; 

@end 

Line.m

@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]; 
} 

我假設這是某種內存管理錯誤,但我所有的嘗試,以補救它失敗。我真的很感激我在這裏做錯了一個解釋。謝謝!

+0

你在做主線程還是後臺線程? – cpjolicoeur

+0

我不知道如何弄清楚,我沒有做任何事情來告訴它在特定的線程上運行。 – turbo

回答

1

當您撥打[self.startTime release]時,您會過度釋放。這是訪問者的工作(setStartTime:)來執行此版本。

代碼中並沒有任何意義,而且是危險的,因爲它留下了懸空伊娃:

currentTime = [[NSDate date] retain]; 
NSLog(@"breakpoint1"); 
life = [currentTime timeIntervalSinceDate:self.startTime]; 
[currentTime release]; 

這應該是:

self.life = [[NSDate date] timeIntervalSinceDate:self.startTime]; 

你得到一個autoreleasepool事實錯誤表明你正在後臺線程上運行它。你的代碼不是線程安全的,所以這會是一個問題。

編輯關於穿線碼,你打電話是怎麼回事beginLifeTracking?那將是我會懷疑你進入錯誤線程的地方。我會非常關心這個autoreleasepool警告。

+0

我該如何解決如果我的代碼是線程安全的或解決這個問題。對不起,但這是我不熟悉的東西。 – turbo

+0

我把它稱之爲碰撞的球類實例。在那個類實例中,當這個球與一條線相碰撞時,這條線被傳遞給另一個方法來處理彈跳,並且我還調用[line beginLifeTracking]以及該線的聲音合成代碼。 (當線路的壽命結束時,聲音停止)。 – turbo

+0

在此處放置一個斷點,並查看您正在使用的線程以及該線程的根。 –

0

這條線:

startTime = [NSDate dateWithTimeIntervalSince1970:0]; 

將覆蓋實例變量startDate具有自動釋放NSDate。在該方法退出後不久,將會釋放該實例併成爲一個懸掛指針。

這是導致您崩潰的原因。

你可能方法應該是這樣的:

-(void)beginLifeTracking { 
    self.startTime = [NSDate dateWithTimeIntervalSince1970:0]; 
    NSLog(@"Time Interval: %@", self.startTime); 
} 

我也註釋掉你的日誌語句,並使其正常工作。

+0

這樣做會在該方法的第一行中引發以下錯誤: 2011-08 -18 11:49:20.228 myProgram [288:5e03] *** __NSAutoreleaseNoPool():類NSCFString的對象0x16d0b0自動釋放,沒有池到位 - 只是泄漏 2011-08-18 11:49:20.207 myProgram [288:307 ] ***由於未捕獲的異常'NSInvalidArgumentException',原因:' - [__ NSDate dateWithTimeIntervalSince1970:]:無法識別的選擇器發送到實例0x16d780' – turbo

+0

'+ dateW ithTimeIntervalSince1970:'是一個類方法,而不是一個實例方法。 –

+0

所以我會把它稱爲[NSDate dateWithTimeIntervalSince1970:0]而不是[[NSDate Date] dateWithTimeIntervalSince 1970]? – turbo