ancyrweb
ancyrweb

Reputation: 1313

Is a value inside an NSDictionary released when removed?

I have something along the line of this :

@implementation ImageLoader
NSMutableDictionary *_tasks;

- (void) loadImageWithURL:(NSURL *)url callback:(SMLoaderCallback)callback {
    NSMutableArray *taskList = [_tasks objectForKey:urlString];
    if (taskList == nil) {
        taskList = [[NSMutableArray alloc] initWithCapacity:5];
        [taskList addObject:callback];
        [_tasks setObject:taskList forKey:urlString];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *image = [[UIImage alloc] initWithData:data];
                for (SMLoaderCallback cb in taskList) {
                    cb(image, nil);
                }
                [_tasks removeObjectForKey:url.absoluteString];
            });
        });
    } else {
        [taskList addObject:callback];
    }
}
@end

In here, I'm trying to queue up image downloads to gain performance (as an exercise only). So I'm keeping a NSDictionary that maps an URL with an array of callbacks to be called whenever the data is downloaded.

Once the image is downloaded, I no longer need this array, so I remove it from the dictionary.

I would like to know if, in this code (with ARC enabled), my array along with the callbacks are correctly released when I call [_tasks removeObjectForKey:url.absoluteString].

Upvotes: 0

Views: 42

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119302

If your project uses ARC and that dictionary is the only thing that is referencing to those values, yes. it will be remove permanently.

ARC keeps track of number of objects that is pointing to some other object and it will remove it as soon as the count reaches 0.

so adding to dictionary -> reference count += 1

removing from dictionary -> reference count -= 1

Somewhe

Upvotes: 1

Related Questions