【问题标题】:Getting allocation count plus one at UIImage in objective-c?在objective-c中的UIImage上获取分配计数加一?
【发布时间】:2010-07-10 06:30:38
【问题描述】:

我在下面的代码中得到分配计数加一。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MasterViewIdentifier"] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellEditingStyleNone;
        UIView* elementView =  [ [UIView alloc] initWithFrame:CGRectMake(5,5,312,480)];
        elementView.tag = 0;
        [cell.contentView addSubview:elementView];
        [elementView release];
    }
    UIView* elementView  = [cell.contentView viewWithTag:0];
    for(UIView* subView in elementView.subviews)
    {
        [subView removeFromSuperview];
    }

    if(indexPath.section==0)
    {
        if(indexPath.row==0)
        {
                   // i have tried like this but getting exception.
            /*
            UIImage *cellBackImag=[UIImage imageNamed:@"celltop.png" ];
            UIImageView* imaeView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 43)];
            imaeView.image=cellBackImag;
            [elementView addSubview:imaeView];
            [imaeView release];
            [cellBackImag release];
             */


            // here I am getting uiimage count allocation count 
            UIImageView* imaeView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"celltop.png" ]];
            imaeView.frame=CGRectMake(0, 0, 300, 43);
            [elementView addSubview:imaeView];
            [imaeView release];

请帮我解决这个问题,谢谢, 马丹·莫汉

【问题讨论】:

    标签: objective-c count uiimage memory-management


    【解决方案1】:

    首先你不应该依赖于保留计数,因为当你将对象传递给某个方法时,所有事情都可能发生在这个对象上,比如有人保留它,再次自动释放它,将它传递给另一个方法等等. 所以这个值是非常不准确的。

    但在您的情况下,(至少)+1 的保留计数是正确的,因为您希望您的图像视图在将其作为子视图添加到elementView 后保持活动状态,因此[element addSubview:imageView] 保留您的图像查看(将 +1 添加到保留计数),然后再次释放它(从 alloc init 中保留 +1)。

    注释掉的代码出现异常的原因是您为cellBackImag 创建了一个自动释放的对象,然后将其释放。在你的方法返回后,自动释放池会在某个时候再次释放图像,然后它就会崩溃。

    所以基本上只使用第二种方法(alloc、init、add、release)而忘记保留计数。如果您担心内存泄漏,您应该看看 Instruments,它是查找各种错误的好工具。

    【讨论】:

    • +1。忽略实际计数,使用适当的内存管理(即,如果您拥有它,您有责任释放它)并使用 Instruments 来查找实际泄漏。
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多