iphone - 自定义 UIView 内存泄漏 - iPhone/iPad/iOS 应用程序开发

标签 iphone objective-c ios xcode memory-management

我有一个 View Controller ,它在 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

最佳答案

去掉这一行的 retain 消息,你应该已经准备就绪:

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

你需要这样做的原因是因为你已经通过调用alloc拥有了这个对象,所以在那个时候,相对引用计数是2

一旦您调用 addSubview:,传入 imageview,引用计数就会增加到 3,然后又回到 2 一旦你在下一行释放它。

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

关于iphone - 自定义 UIView 内存泄漏 - iPhone/iPad/iOS 应用程序开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4982402/

相关文章:

iphone - ViewController = _ViewController 的意思

ios - Ringly 为 iOS 使用了哪些 API?

ios - 将消息从父 View Controller 发送到容器 View

ios - 如何获得屏幕上显示的图像的准确持续时间计时器?

iOS - 信用卡 + PayPal 交易不是通过应用内购买

ios - iPad 上的 iPhone 应用程序 : drawViewHierarchyInRect causes glitch

ios - Master-DetailView 应用程序

objective-c - XCode 4 if (self = [super init]) 问题

iphone - 在 iOS 7 上禁用 SKStoreProductViewController 速率

ios - 可重用单元格和阵列的问题