代码之家  ›  专栏  ›  技术社区  ›  Steve A

又一个泄露的NSMutableDictionary帖子

  •  1
  • Steve A  · 技术社区  · 14 年前

    我的头撞在显示器上好几个小时了(也读过类似的帖子)。我还是被难住了。

    @interface TeamsTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> 
    {
        NSMutableArray *teamsArray;
    }
    

    我将数组分配到 -viewDidLoad

    -(void)viewDidLoad 
    {
        [super viewDidLoad];
    
        // Inititalize the mutablearray that will store the xml for the table.
        teamsArray = [[NSMutableArray alloc] init];
    }
    
    -(void)dealloc 
    {
        [teamsArray release];
    
        [super dealloc];
    }
    

    每次 -viewWillAppear ,我调用loadData来重新加载数据(因为数据可以更改)。在这篇文章中(当我试图找到我的漏洞时),我已经对数据进行了硬编码。显示了所报告的泄漏位置。(重新显示表视图时发生泄漏。)

    -(void)loadData
    {
        // Empty any objects that are already in the array.
        [teamsArray removeAllObjects];
    
        // Fill a dictionary (normally looping through a file, but hardcoded for leak hunting).
        NSMutableDictionary *oneTeamDictionary = [NSMutableDictionary dictionary];
    
        [oneTeamDictionary setObject:@"100"         forKey:@"basenumber"];
        [oneTeamDictionary setObject:@"Team Name"   forKey:@"teamname"];
        [oneTeamDictionary setObject:@"XYZ"         forKey:@"teamabbr"];
        [oneTeamDictionary setObject:@"USA"         forKey:@"countryabbr"];
        [oneTeamDictionary setObject:@"Joe"         forKey:@"manager"];
    
        // Add this team to the array used to display table data.
        [teamsArray addObject:[oneTeamDictionary copy]];  // Leaks Malloc 32 bytes and _NSCFDictionary 48 bytes here.
    
        // Reload the table view with new data.
        [self.tableView reloadData];
    }
    

    在我的新手状态下,我认为 [teamsArray release] 将释放dictionary对象。我还尝试过使用“alloc]init]”来创建字典,以及释放和重新分配teamsArray(而不是调用 removeAllObjects

    2 回复  |  直到 13 年前
        1
  •  2
  •   Jonah    14 年前

    如果使用的是托管内存(而不是垃圾回收),则此方法在返回新对象之前会保留它。但是,方法的调用程序负责释放返回的对象。

    你为什么不打电话给:

    [teamsArray addObject:oneTeamDictionary];
    
        2
  •  0
  •   Jay    14 年前