2010-12-16 74 views
0

我有一個輔助方法,爲我加載圖像。我希望能夠使用這個代碼都在我的應用程序,所以我創造了這個:如何在獲取UIImageView時避免此內存泄漏?

+(UIImageView *) getSignature: (NSString *) aPONumber { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    NSString *newPath =[documentsPath stringByAppendingPathComponent: [NSString stringWithFormat:@"%@-signature.jpg", [aPONumber stringByReplacingOccurrencesOfString:@"/" withString:@""]]]; 

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:newPath]; 
    if(fileExists) 
    { 

     return [[UIImageView alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:newPath]]; 
    } else { 
     return nil; 
    } 
} 

這將是使用自動釋放的好地方?像這樣:

return [[[UIImageView alloc] initWithImage:[[[UIImage alloc] initWithContentsOfFile:newPath] autorelease]]autorelease]; 

回答

1

簡答:是的。

你可以在那裏使用autorelease,不用擔心釋放你的UIImageViews或UIImages了。只需將它們添加到UIView中,一旦它們從UIView中移除或UIView被釋放,它們將自動解除分配。