Leonardo
Leonardo

Reputation: 9857

Incorrect object allocation/deallocation in objective-c

I have run a profiler with allocation and memory leak options. I discover that object related to a table cell never get released. By analyzing further I found that the problem is caused by a custom image I store in cell. I explain better:

I have an object extending table cell:

@interface IP2TableViewCell : UITableViewCell

@property(nonatomic,weak) IBOutlet UIImageView *background;
@property(nonatomic,weak) IBOutlet UIImageView *thumbnail;
@property(nonatomic,weak) IBOutlet UILabel *cellTitle;
@property(nonatomic,weak) IBOutlet UILabel *cellDescr;

@end 

with just simple @synthesize in .m class file and nothing else.

I then made a class extending UIImage, which has this relevant initMethod I am using. I have to say that self=[super..] is a fragment of code I quite don't understand that I borrow from the auto generated code for view controllers, which is if(self=[super initWith...)

-(ExtendedImage*)initWithPath:(NSString*)path andOptions:(NSDictionary*)opt {
   self=[super initWithContensOfFile:path];
   self.options=opt;
   return self;
}

this is where the allocation problem start to show. I have a factory that build the image by calling init method above, then later the image is added to the cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *obj = [fetchedResultsController objectAtIndexPath:indexPath];
    IP2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];
    cell.cellTitle.text=[obj objectForKey:@"cellTitle"];
    NSDictionary *options = [NSDictionary dictionaryWithObject:indexPath forKey:@"indexPath"];
    ExtendedImage *ei = [imageCache imageWithPath:@"/path/to/file" withOptions:options];
    cell.thumbnail.image=ei;
    return cell;
}

In the profiler it is shown that the ExtendedImage live forever, and never gets deallocated, and also the table cell it is not freed. If in other case I do

cell.thumbnail.image=[UIImage imageWithContentsOfFile:@"/path/to/file"];

all is behaving fine, and the profiler does not shown anything wrong, and objects, cell in particular, get correctly deallocated.

At this point I have two simple questions.

thanks

Upvotes: 1

Views: 239

Answers (1)

user23743
user23743

Reputation:

You have an imageCache: this suggests that you're actually trying to cache the images. That will, by definition, have the effect of causing them to hang around while you're not using them. You need to consider your cache strategy: do you really need to cache images at all? If so, for how long? When can you empty an image from the cache?

You could consider using purgeable memory (integrating with NSCache) for your cache, so that the operating system can manage throwing away your images when they are getting in the way.

Upvotes: 1

Related Questions