Memory management is confusing!

Discussion in 'iOS Programming' started by nashyo, Mar 2, 2013.

  1. nashyo macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol
    #1
    I have this arrangement for my app, which downloads resources from a web service.

    NSOperationQueue > NSOperation > ViewController > CustomTableViewCell

    I have a weak delegate callback from NSOperation to the view controller.

    This arrangement is fine. When my view controller dismisses, these objects stay in memory until the download finishes. Then they all deallocate nicely.

    But if I bring the view controller back on screen during the download, the table view populates new cells (has new memory addresses). So the new cell at position 0 in the table view isn't receiving progress updates.

    Progress is frequently sent via a block

    I call this block from the view controller
    Code:
    -(void)downloadResource:(Resource *)theResource
             withProgress:(void (^)(NSNumber *progress))progressCallback
              withSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successCallback
              withFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureCallback
    Which gets it's progress from a block

    Code:
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            
            float progress = (float)totalBytesRead / (float)totalBytesExpectedToRead;
            
            progressCallback([NSNumber numberWithFloat:progress]);
            
        }];
    I'm very confused. If anyone can shed any light on this, I would appreciate it.

    Many thanks
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    This is a job for KVO. Actually it's the classic job for KVO.

    You need a model layer class that manages all the downloads. It's independent from the UI. It maintains a list of downloads. When the UI appears the rows observe the downloads and report their state, including progress. If the UI goes away the rows just stop observing the downloads.

    Don't think you can use blocks for this, at least not to communicate to the UI.
     

Share This Page