Reading UIImage from Document folder
I need to read the image from document folder and prepare UIImage out of that. but when I call this function everytime memory get increasing and for large scale image this scale is large. following is same code
-(UIImage*) GetSavedImageWithName:(NSString*) aFileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
[str appendString:documentsDirectory];
[str appendString:@"/"];
[str appendString:aFileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:str];
NSData *dataToWrite = nil;
UIImage* image = nil;
if(!success)
{
}
else
{
dataToWrite = [[NSData alloc] initWithContentsOfFile:str];
image = [UIImage开发者_Python百科 imageWithData:dataToWrite]; YES;
}
if(dataToWrite)
{
[dataToWrite release];
dataToWrite = nil;
}
if(str)
{
[str release];
str = nil;
}
if(fileManager)
{
[fileManager release];
fileManager = nil;
}
return image;
}
Calling this way
[self SetFrontViewImage:[self GetSavedImageWithName:@"Edited"]];
I am not able to find where it is getting leak.
Thanks,
Sagar
It's consuming more memory because you're reading file-converting it to data-converting it to image and again using class method.
So instead use following way:
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:str];
UIImage* image = nil;
if(!success)
{
return nil;
}
else
{
image = [[UIImage alloc] initWithContentsOfFile:str]; YES;
}
return [image autorelease];
}
And don't release your file manager object. It is an auto release object.
Because the returned UIImage is an autorelease object. It means the run loop will release these autorelease objects later. Before it release those autorelease objects, the memory space will grow up, especially when loading images with loop or a work thread.
精彩评论