2

I have an arc-enabled project which has PersonModel class:

// .h
@interface PersonModel : NSObject

@property (strong, nonatomic) NSString *photoUrl;
@property (strong, nonatomic) UIImage *photo;
@property (strong, nonatomic) NSString *fio;

@end

// .m
@implementation PersonModel

@synthesize photoUrl;
@synthesize photo = _photo;
@synthesize fio;

- (UIImage *)photo
{
    if (_photo == nil && self.photoUrl) {
        _photo = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoUrl]]];
    }

    return _photo;
}

@end

photo getter is invoked using gcd:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    UIImage *cellImage = model.photo;

});

On line

_photo = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoUrl]]];

Instruments shows 100% memory leak. As far as I know arc does not work on threads except main thread. So is there any way of fixing this issue?

Dmitry
  • 245
  • 1
  • 2
  • 9
  • 5
    ARC works on all threads, and is thread-safe. Instruments shows you where the leaked block was originally allocated. You're doing something with that image somewhere else that's retaining it and not releasing it. Look at [this answer](http://stackoverflow.com/a/14891837/77567) for help getting Instruments to show you every `retain`, `release`, and `autorelease` of the image. – rob mayoff Mar 31 '13 at 22:30
  • @robmayoff thank you for this helpful link. Odd thing happened. I was having memory leak when testing on simulator but when I switched to iphone memory leak magically disappeared... Guess it was simulator related problem. – Dmitry Apr 01 '13 at 08:43
  • dispatch_get_global_queue returns a concurrent queue. If you invoke the photo getter on the same model twice, using dispatch_async to that queue, both gets will be running on a different threads. Since photo is a non-atomic property, I wouldn't like to take bets about what happens if you write to it on two threads simultaneously. I would expect ARC to be thread safe in that regard, but you can certainly get other problems. – Airsource Ltd Jul 08 '14 at 16:21

0 Answers0