2012-03-13 49 views
0

我使用這個設置在NSDisctionary一個鍵的值:EXC壞訪問錯誤,除非值是硬編碼

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 

NSLog(@"touchesEnded currentcolor: %@", currentColor); 

if (currentTool == @"paint") { 
NSLog(@"End Paint"); 
CGPoint point = [[touches anyObject] locationInView:self.view]; 
MaskPath * myNewPath = [mapView.drawthis containsPoint:point]; 
[myNewPath.attributes setValue:currentColor forKey:@"fill"]; 
[mapView setNeedsDisplay]; 

} else { 
NSLog(@"End Pattern"); 

currentColor = @"1.png"; 

CGPoint point = [[touches anyObject] locationInView:self.view]; 
MaskPath * myNewPath = [mapView.drawthis containsPoint:point]; 
[myNewPath.attributes setValue:currentColor forKey:@"fill"]; 
[mapView setNeedsDisplay]; 
} 
} 

如果我嘗試登錄currentColor的值與EXC壞訪問應用程序崩潰(第3行) 如果我註銷並使用硬編碼值,一切正常。它也適用於if語句的第一部分。我已經檢查過指定currentColor的函數,它正在提供正確的值。如果我在這一點硬編碼currentColor的值,它工作正常。我運行了分析器,並且沒有內存泄漏或問題。我怎麼能跟蹤這個問題呢?

+0

你能證明申報並指定顏色的代碼? – 2012-03-13 20:43:06

+0

如果它與'NSLog'崩潰,那麼它絕對與'NSDictionary'無關。你在哪裏設置currentColor;我敢打賭,你沒有正確保留:) – deanWombourne 2012-03-13 20:44:29

+0

這是因爲'currentColor'已被釋放。提供聲明'currentColor'的代碼,以及將其設置在'touchesEnded:withEvent:'方法之外的位置。 – Jeremy 2012-03-13 20:44:42

回答

1

一個明顯的問題是,你正在使用一個autorelease變量,如你的例子所證明的。最有可能的是你在這種方法之外做同樣的事情。

我建議你做currentColor屬性:

@property (nonatomic, retain) NSString *currentColor; 

然後,設置它,你會做這樣的事情:

self.currentColor = @"SomeColor"; 

既然你宣佈了保留currentColor屬性,當你將它傳遞給你的NSLog時不會得到錯誤的訪問:

NSLog(@"This is my color: %@", self.currentColor); 

如果你已經完成的一currentColor財產,你只是分配實例變量,那麼你應該做的:

currentColor = [NSString alloc] initWithString:@"Foo"]; 

概括起來:

1. self.currentColor = @"Foo"; //<-This is automagically retained 
2. currentColor = [NSString alloc] initWithString:@"Foo"]; //<-Accessing the ivar directly, so you must ownify the string :D