【问题标题】:Iterate through NSMutableArray to add object in array遍历 NSMutableArray 以在数组中添加对象
【发布时间】:2015-11-02 07:54:52
【问题描述】:

我收到了一系列公司的 JSON 响应。 然后我遍历数组以便将它们添加为 Company 对象。我的问题是,如果我在循环内执行[[Company alloc]init];,我将造成内存泄漏。如果我 alloc-init 退出循环,我的所有值都是相同的。最好的方法是什么? 代码如下:

resultArray = [[NSMutableArray alloc]init];
responseArray = [allDataDictionary objectForKey:@"companies"];

 Company *com = [[Company alloc]init];
            //Looping through the array and creating the objects Movie and adding them on a new array that will hold the objects
            for(int i=0;i<responseArray.count;i++){


                helperDictionary =(NSDictionary*)[responseArray objectAtIndex:i];

                com.title = [helperDictionary objectForKey:@"company_title"];
                NSLog(@"company title %@",com.title);
                [resultArray addObject:com];

            }

公司名称在结果数组中始终是相同的值。如果我将 Company alloc-init 放入循环中,则值是正确的。

【问题讨论】:

    标签: ios objective-c nsmutablearray


    【解决方案1】:

    我假设您想为字典中的每个条目创建一个新的Company 对象?在这种情况下,您必须每次都创建一个新实例:

    for (NSDictionary *dict in responseArray) {
        Company company = [[Company new] autorelease];
        company.title = dict[@"company_title"];
        [resultArray addObject:company];
    }
    

    【讨论】:

    • 每次使用相同的变量名创建新实例会导致泄漏,对吧?
    • @BlackM 不。您正在数组中存储对对象的引用。
    • 我读到如果你在一个循环中初始化一个对象,你就会失去对该对象的引用并且它不能被释放。这是完全错误的吗?谢谢你的回答
    • 好吧,当您让数组管理对象时,您不会丢失它。如果您使用手动引用计数,那么如果没有最后一行,就会出现内存泄漏。
    • 如果使用手动内存管理,那company加入数组后不需要释放吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多