2012-03-13 56 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