I've got NSURLSession, that downloads new user profiles from server, then for each profile downloads array of photos, and than stores in Core Data. Every time the user reaches this screen i stop downloading tasks, clear Core Data, than fill it again. The problem is, that cancel() function is async, so it manages to save some profiles AFTER i cleared Core Data. Moreover, these profiles can be without some data thanks to datatask cancel. So, the question is as follows - how to correctly finish download tasks and after that clear core data? Thanks in advance.
Asked
Active
Viewed 613 times
1 Answers
2
I would recommend using NSOperation
class for what you need.
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/
You should wrap-up operation for downloading data into NSOperation class and before you add results to CoreData you can check if NSOperation was cancelled in between.
@interface DownloadOperation: NSOperation
@end
@implementation DownloadOperation
- (void)main {
@autoreleasepool {
[Server downloadDataFromServer:^(id results) {
if (self.isCancelled == NO)
{
[CoreData saveResults:results];
}
}];
}
}
@end
You add your operation to NSOperationQueue:
NSOperationQueue *queue= [[NSOperationQueue alloc] init];
[queue addOperation:[[DownloadOperation alloc] init]];
And you can cancel it by calling:
[operation cancel];
or canceling all operations:
[queue cancelAllOperations];

Grzegorz Krukowski
- 18,081
- 5
- 50
- 71
-
Well, i understand. But there is one more trouble. When the user fast leaves the collection view controller, and than loads it again - i delete objects from Core Data, but old controller instance continues building collection view for a few seconds before deinit, it tries to load removed models, which causes data fault and crash. How can i deal with this? – Nikita Semenov Sep 02 '15 at 10:13