大家好,有人可以建议如何解决下面代码中的内存泄漏问题
我已经尝试了几乎每种组合的发布和自动释放我能想到但每次应用程序崩溃或泄漏仍然存在
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//get refereance to the textfield
UITextField *currentTextField = (UITextField*)[self.view viewWithTag:200];
//check which picker
if(pickerView.tag ==1)
{
// Only calls the following code if component "0" has changed.
if (component == 0) {
// Sets the global integer "component0Row" to the currently selected row of component "0"
component0Row = row;
// Loads the new values for the selector into a new array in order to reload the data.
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
currentValues = newValues;
// Reloads the data of component "1".
[pickerView reloadComponent:1];
}
//run the selector logic
[self textFieldDidEndEditing:currentTextField];
}
希望有人可以提供建议
非常感谢答案 0 :(得分:2)
你的问题是这两行:
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
currentValues = newValues;
第一行分配了一个新的NSMutableArray实例。第二行将指针从newValues
复制到currentValues
,覆盖 currentValues
中的指针值。任何currentValues
指向的东西都会丢失。那是泄漏。
你可以这样解决:
newValues = [[NSMutableArray alloc] init...
[currentValues release];
currentValues = newValues;
这样,currentValues
指向的任何内容都会在您失去对它的访问权限之前减少其引用计数。
您还可以通过将currentValues作为Objective-C属性并通过self.currentValues
或[self setCurrentValues:]
使用访问器方法来解决问题;这些方法将为您处理保留/释放。
答案 1 :(得分:0)
永远不会发布您的NSMutableArray分配。
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
如果您不再需要它,您应该自动发布或稍后发布。
答案 2 :(得分:0)
不确定如何定义currentValues,但这应该没有泄漏:
在你的.h文件中:
@property (nonatomic, retain) NSArray * currentValues;
在您的.m文件中:
@synthesize currentValues;
self.currentValues = newValues;