Search code examples
iphoneobjective-cios4memory-managementmemory-leaks

How the memory of those object been released that is not been allocated?


I have initialize an image, like:

    NSString *url=[NSString stringWithFormat:@"url/%@",[self.urlOfImagesToDownload objectAtIndex:i]];
    UIImage *myImage=[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: url]]];
    NSLog(@"%d byte of data", [[NSData dataWithContentsOfURL: [NSURL URLWithString: url]] length]); 

    if (myImage)
    {
        NSString *jpegFilePath = [NSString stringWithFormat:@"%@/%@.jpg",[self pathForDocumentDirectory],[self.idOfImagesToDownload objectAtIndex:i]];
        NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(myImage, 1.0f)];//1.0f = 100% quality
        [data1 writeToFile:jpegFilePath atomically:YES];
    }

Now how can I release the memory of NSString *jpegFilePath and NSData *data1

And if I have a method:

    -(void) changeImageSlide{
     totalNoOfImages=[copyOf_myGlobleArrayOfImageIds count];
        if (imageCounter>=totalNoOfImages-1) {
            imageCounter=0;
        }
        NSString *str = [NSString stringWithFormat:@"%@.jpg",[copyOf_myGlobleArrayOfImageIds objectAtIndex:imageCounter]];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullImgNm=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:str]];
        //=(3*imageCounter+4)%25;
UIImage *img=[UIImage imageWithContentsOfFile:fullImgNm];
        [mainSlideShowImageView setImage:img];
        [mainSlideShowImageView setTag:[[copyOf_myGlobleArrayOfImageIds objectAtIndex:imageCounter] intValue]];     
        imageCounter++;

    }

It's been called with Timer(for implementing slide show), how can I release memory here in this one, from UIImage *img and NSString *FullImageName.

Along with that, how to be assured that once another image have loaded to imageView previous image is been released from memory?


Solution

  • Neither method needs memory released for the vars you mention because they use class methods which provide autoreleased instances.

    but...

    You will leak in method one for

    UIImage *myImage=[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: url]]];

    because there you init the object and thus take ownership. You need to release this at the end of the method