【问题标题】:Custom UIView Leaking Memory - iPhone/iPad/iOS App Development自定义 UIView 内存泄漏 - iPhone/iPad/iOS 应用程序开发
【发布时间】:2011-02-13 04:16:38
【问题描述】:

我有一个视图控制器,它在 uiscrollview 中重复重新定位 6 个项目。但是,即使我将 uiscrollview 中的项目数限制为 6,当我更新它们的位置和图像时,我仍然会泄漏内存。有人可以让我知道以下代表 uiscrollview 中的单元的代码是否正确编码? startLoad 是我在重新加载图像后调用的方法。

#import "ScrollUnit.h"

@implementation ScrollUnit
@synthesize index;
@synthesize ProductToDisplay;

- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
    }
    return self;
}        

-(void)startLoad
{   
    [imageview removeFromSuperview];
    [imageview release];

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                              selector:@selector(loadImage) 
                                                object:nil];

    [queue addOperation:operation];
    [operation release];
}

-(void)loadImage 
{
    NSString *myimageName = [self.ProductToDisplay valueForKey:IMAGEKEY];
    NSString *myimageUrl = [NSString stringWithFormat:@"%@/%@",IMAGE_SERVICE,myimageName];

    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myimageUrl]];

    UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
    [imageData release];
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
}

- (void)displayImage:(UIImage *)image 
{   
    imageview = [[[UIImageView alloc] initWithFrame:CGRectMake(9, 0, 320, 320)]retain];
    imageview.contentMode = UIViewContentModeScaleAspectFit;
    imageview.backgroundColor = [UIColor whiteColor];
    imageview.image = image;
    [self addSubview:imageview];
    [imageview release];
    //[image release];
}

- (void)dealloc {
    [super dealloc];
}

@end

【问题讨论】:

    标签: iphone objective-c ios xcode memory-management


    【解决方案1】:

    去掉这一行上的retain 消息,你应该已经准备好了:

    imageview = [[[UIImageView alloc] initWithFrame:CGRectMake(9, 0, 320, 320)]retain];
    

    之所以需要这样做是因为您已经通过调用alloc拥有该对象,所以此时相对引用计数为2

    一旦你调用addSubview:,传入imageview,引用计数就会上升到3,然后当你在下一行release它时,引用计数就会下降到2

    因此,一旦该对象在-dealloc 中发送release,您仍然会卡住,因为引用计数现在是1,而不是您预期的0

    【讨论】:

      【解决方案2】:

      还有另一件小事可能会出错(或不会出错)。在 displayImage 方法中分配 imageview 之前,您不会释放它。只要只调用 startLoad 就可以了,但是如果从外部调用 displayImage ,那么你仍然会泄漏。

      您可能希望将属性与 retain 一起使用,然后合成 getter 和 setter 方法。这样,iOS 将在保留新分配的对象之前释放您之前的分配。也就是说,您需要在创建图像视图时正确释放它,并且您必须使用“self.imageview”以确保您使用设置器(setImageview)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多