Merge pull request #2116 from dreampiggy/feature_invalidate_SDWebImageDownloader

Add a public API to allow user to invalidate URLSession used in SDWebImageDownloader to avoid memory leak on non-singleton instance
This commit is contained in:
DreamPiggy 2017-11-28 20:17:57 +08:00 committed by GitHub
commit dbc6b6995d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 3 deletions

View File

@ -162,7 +162,7 @@ typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterB
/**
* Creates an instance of a downloader with specified session configuration.
* *Note*: `timeoutIntervalForRequest` is going to be overwritten.
* @note `timeoutIntervalForRequest` is going to be overwritten.
* @return new instance of downloader class
*/
- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
@ -239,11 +239,18 @@ typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterB
/**
* Forces SDWebImageDownloader to create and use a new NSURLSession that is
* initialized with the given configuration.
* *Note*: All existing download operations in the queue will be cancelled.
* *Note*: `timeoutIntervalForRequest` is going to be overwritten.
* @note All existing download operations in the queue will be cancelled.
* @note `timeoutIntervalForRequest` is going to be overwritten.
*
* @param sessionConfiguration The configuration to use for the new NSURLSession
*/
- (void)createNewSessionWithConfiguration:(nonnull NSURLSessionConfiguration *)sessionConfiguration;
/**
* Invalidates the managed session, optionally canceling pending operations.
* @note If you use custom downloader instead of the shared downloader, you need call this method when you do not use it to avoid memory leak
* @param cancelPendingOperations Whether or not to cancel pending operations.
*/
- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations;
@end

View File

@ -107,6 +107,14 @@
delegateQueue:nil];
}
- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations {
if (cancelPendingOperations) {
[self.session invalidateAndCancel];
} else {
[self.session finishTasksAndInvalidate];
}
}
- (void)dealloc {
[self.session invalidateAndCancel];
self.session = nil;

View File

@ -61,6 +61,7 @@
- (void)test01ThatSharedDownloaderIsNotEqualToInitDownloader {
SDWebImageDownloader *downloader = [[SDWebImageDownloader alloc] init];
expect(downloader).toNot.equal([SDWebImageDownloader sharedDownloader]);
[downloader invalidateSessionAndCancel:YES];
}
- (void)test02ThatByDefaultDownloaderSetsTheAcceptHTTPHeader {
@ -377,6 +378,7 @@
}];
[self waitForExpectationsWithCommonTimeout];
[downloader invalidateSessionAndCancel:YES];
}
@end