Download images in LIFO order instead of FIFO #294

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+303 −3
Split
@@ -67,6 +67,8 @@
5376131E155AD0D5005750A4 /* SDWebImagePrefetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 53922D91148C56230056699D /* SDWebImagePrefetcher.h */; settings = {ATTRIBUTES = (Public, ); }; };
5376131F155AD0D5005750A4 /* UIButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 53922D93148C56230056699D /* UIButton+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; };
53761320155AD0D5005750A4 /* UIImageView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 53922D95148C56230056699D /* UIImageView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; };
+ BFE8F33F16C910D300551AA6 /* LIFOOperationQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = BFE8F33D16C910D300551AA6 /* LIFOOperationQueue.h */; };
+ BFE8F34016C910D300551AA6 /* LIFOOperationQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = BFE8F33E16C910D300551AA6 /* LIFOOperationQueue.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -106,6 +108,8 @@
53922D96148C56230056699D /* UIImageView+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+WebCache.m"; path = "SDWebImage/UIImageView+WebCache.m"; sourceTree = SOURCE_ROOT; };
53FB893F14D35D1A0020B787 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
53FB894814D35E9E0020B787 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
+ BFE8F33D16C910D300551AA6 /* LIFOOperationQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LIFOOperationQueue.h; path = SDWebImage/LIFOOperationQueue/LIFOOperationQueue.h; sourceTree = SOURCE_ROOT; };
+ BFE8F33E16C910D300551AA6 /* LIFOOperationQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = LIFOOperationQueue.m; path = SDWebImage/LIFOOperationQueue/LIFOOperationQueue.m; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -211,6 +215,7 @@
53922DAC148C56DD0056699D /* Utils */ = {
isa = PBXGroup;
children = (
+ 9ECE24BB16C55A0800A1793A /* LIFOOperationQueue */,
53922D8E148C56230056699D /* SDWebImageManager.h */,
53922D8F148C56230056699D /* SDWebImageManager.m */,
53922D89148C56230056699D /* SDWebImageDecoder.h */,
@@ -221,6 +226,16 @@
name = Utils;
sourceTree = "<group>";
};
+ 9ECE24BB16C55A0800A1793A /* LIFOOperationQueue */ = {
+ isa = PBXGroup;
+ children = (
+ BFE8F33D16C910D300551AA6 /* LIFOOperationQueue.h */,
+ BFE8F33E16C910D300551AA6 /* LIFOOperationQueue.m */,
+ );
+ name = LIFOOperationQueue;
+ path = "LIFOOperationQueue-master";
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
@@ -256,6 +271,7 @@
53761320155AD0D5005750A4 /* UIImageView+WebCache.h in Headers */,
530E49E816464C25002868E7 /* SDWebImageOperation.h in Headers */,
530E49EA16464C7C002868E7 /* SDWebImageDownloaderOperation.h in Headers */,
+ BFE8F33F16C910D300551AA6 /* LIFOOperationQueue.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -386,6 +402,7 @@
5376130F155AD0D5005750A4 /* UIImageView+WebCache.m in Sources */,
530E49EC16464C84002868E7 /* SDWebImageDownloaderOperation.m in Sources */,
53406750167780C40042B59E /* SDWebImageCompat.m in Sources */,
+ BFE8F34016C910D300551AA6 /* LIFOOperationQueue.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -0,0 +1,7 @@
+Copyright (c) 2012 Ben Harris
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
+//
+// LIFOOperationQueue.h
+//
+// Created by Ben Harris on 8/19/12.
+//
+#import <Foundation/Foundation.h>
+
+@interface LIFOOperationQueue : NSObject
+
+@property (nonatomic) NSInteger maxConcurrentOperationCount;
+@property (nonatomic, strong) NSMutableArray *operations;
+
+- (id)initWithMaxConcurrentOperationCount:(int)maxOps;
+- (void)addOperation:(NSOperation *)op;
+- (void)addOperationWithBlock:(void (^)(void))block;
+- (void)cancelAllOperations;
+
+@end
@@ -0,0 +1,162 @@
+//
+// LIFOOperationQueue.m
+//
+// Created by Ben Harris on 8/19/12.
+//
+
+#import "LIFOOperationQueue.h"
+
+@interface LIFOOperationQueue ()
+
+@property (nonatomic, strong) NSMutableArray *runningOperations;
+
+- (void)startNextOperation;
+- (void)startOperation:(NSOperation *)op;
+
+@end
+
+@implementation LIFOOperationQueue
+
+@synthesize maxConcurrentOperationCount;
+@synthesize operations;
+@synthesize runningOperations;
+
+#pragma mark - Initialization
+
+- (id)init {
+ self = [super init];
+
+ if (self) {
+ self.operations = [NSMutableArray array];
+ self.runningOperations = [NSMutableArray array];
+ }
+
+ return self;
+}
+
+- (id)initWithMaxConcurrentOperationCount:(int)maxOps {
+ self = [self init];
+
+ if (self) {
+ self.maxConcurrentOperationCount = maxOps;
+ }
+
+ return self;
+}
+
+#pragma mark - Operation Management
+
+//
+// Adds an operation to the front of the queue
+// Also starts operation on an open thread if possible
+//
+
+- (void)addOperation:(NSOperation *)op {
+ if ( [self.operations containsObject:op] )
+ {
+ if (!op.isExecuting)
+ {
+ [self.operations removeObject:op];
+ [self.operations insertObject:op atIndex:0];
+ }
+ }
+ else
+ [self.operations insertObject:op atIndex:0];
+
+ if ( (int)self.runningOperations.count < self.maxConcurrentOperationCount ) {
+ [self startNextOperation];
+ }
+}
+
+//
+// Helper method that creates an NSBlockOperation and adds to the queue
+//
+
+- (void)addOperationWithBlock:(void (^)(void))block {
+ NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:block];
+
+ [self addOperation:op];
+}
+
+//
+// Attempts to cancel all operations
+//
+
+- (void)cancelAllOperations {
+ self.operations = [NSMutableArray array];
+
+ for (int i = 0; i < (int)self.runningOperations.count; i++) {
+ NSOperation *runningOp = [self.runningOperations objectAtIndex:i];
+ [runningOp cancel];
+
+ [self.runningOperations removeObject:runningOp];
+ i--;
+ }
+}
+
+#pragma mark - Running Operations
+
+//
+// Finds next operation and starts on first open thread
+//
+
+- (void)startNextOperation {
+ if ( !self.operations.count ) {
+ return;
+ }
+ if ( (int)self.runningOperations.count < self.maxConcurrentOperationCount ) {
+ NSOperation *nextOp = [self nextOperation];
+ if (nextOp) {
+ if ( !nextOp.isExecuting ) {
+ [self startOperation:nextOp];
+ }
+ else {
+ [self startNextOperation];
+ }
+ }
+ }
+}
+
+//
+// Starts operations
+//
+
+- (void)startOperation:(NSOperation *)op {
+ void (^completion)() = [op.completionBlock copy];
+
+ NSOperation *blockOp = op;
+
+ [op setCompletionBlock:^{
+ if (completion) {
+ completion();
+ }
+
+ [self.runningOperations removeObject:blockOp];
+ [self.operations removeObject:blockOp];
+
+ [self startNextOperation];
@NachoSoto

NachoSoto Feb 15, 2013

Contributor

This seems like a really hacky way to detect finished operations. I would recommend implementing it similar to how NSOperationQueue works and use KVO on isFinished.

+ }];
+
+ [self.runningOperations addObject:op];
+
+ [op start];
+}
+
+#pragma mark - Queue Information
+
+//
+// Returns next operation that is not already running
+//
+
+- (NSOperation *)nextOperation {
+ for (int i = 0; i < (int)self.operations.count; i++) {
+ NSOperation *operation = [self.operations objectAtIndex:i];
+ if ( ![self.runningOperations containsObject:operation] && !operation.isExecuting && operation.isReady ) {
+ return operation;
+ }
+ }
+
+ return nil;
+}
+
+@end
@@ -0,0 +1,77 @@
+LIFOOperationQueue
+==================
+
+A last-in-first-out NSOperation queue written in Objective-C.
+
+What's it for?
+-------------
+
+A LIFO queue can help prioritize new operations over old ones. One such example would be loading images in a `UITableView`. The LIFO approach will ensure that images on screen take higher priority than those a user has already scrolled past.
+
+How does it work?
+-----------------
+
+LIFOOperationQueue is very much like `NSOperationQueue`. Just like the native implementation, you can configure the maximum number of concurrent operations. The only difference is that operations are added to the front of the queue and `NSOperationQueuePriority` has no effect. Initialization looks like this:
+
+ // initialize LIFOOperationQueue with a maximum thread count of 4
+ LIFOOperationQueue *operationQueue = [[LIFOOperationQueue alloc] initWithMaxConcurrentOperationCount:4];
+
+Here are some quick examples of loading images in a `UITableView` with [AFNetworking](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CEcQFjAA&url=https%3A%2F%2Fgithub.com%2FAFNetworking%2FAFNetworking&ei=jTwxUNnPNY6NigLmuYHoAw&usg=AFQjCNE6c3SnPVzdrmQ1-UQ5mEf8Kl9JXg&sig2=WtTzATbO_YTH888N5ZEcAQ) and LIFOOperationQueue.
+
+ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ // create cell
+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
+ if (cell == nil) {
+ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
+ }
+
+ // initialize imageView.image
+ cell.imageView.image = [UIImage imageNamed:@"blankImage.png"];
+
+ // create image request
+ NSURL *imageUrl = [NSURL URLWithString:@"http://www.i-love-cats.com/software/Adorable-Cats-Screensaver.jpg"];
+ NSURLRequest *urlRequest = [NSURLRequest requestWithURL:imageUrl];
+ AFImageRequestOperation *imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest success:^(UIImage *image) {
+ UITableViewCell updateCell = [tableView cellForRowAtIndexPath:indexPath];
+ if (updateCell)
+ updateCell.imageView.image = image;
+ }];
+
+ // add to LIFOOperationQueue
+ [self.operationQueue addOperation:imageRequestOperation];
+
+ return cell;
+ }
+
+The code above would prioritize the latest cell's image over those that may not be on screen anymore. You can accomplish the same thing without AFNetworking by using blocks.
+
+ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+ // create cell
+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
+ if (cell == nil) {
+ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
+ }
+
+ // initialize imageView.image
+ cell.imageView.image = [UIImage imageNamed:@"blankImage.png"];
+
+ // add block to LIFOOperationQueue
+ [self.operationQueue addOperationWithBlock:^{
+ UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
+
+ // be sure to display image on main thread
+ dispatch_async(dispatch_get_main_queue(), ^{
+ UITableViewCell updateCell = [tableView cellForRowAtIndexPath:indexPath];
+ if (updateCell)
+ updateCell.imageView.image = image;
+ });
+ }];
+
+ return cell;
+ }
+
+`addOperationWithBlock:` executes the block asynchronously by default.
+
+License
+-------
+LIFOOperationQueue is available under the MIT license. See the LICENSE file for more info.
@@ -0,0 +1,3 @@
+LIFOOperationQueue was taken from:
+https://github.com/bharris47/LIFOOperationQueue (master @dd738256f6)
+
@@ -9,6 +9,7 @@
#import "SDWebImageDownloader.h"
#import "SDWebImageDownloaderOperation.h"
#import <ImageIO/ImageIO.h>
+#import "LIFOOperationQueue.h"
NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
@@ -18,7 +19,8 @@
@interface SDWebImageDownloader ()
-@property (strong, nonatomic) NSOperationQueue *downloadQueue;
+@property (strong, nonatomic) LIFOOperationQueue *downloadQueue;
+@property (strong, nonatomic) NSMutableDictionary *operationsDict;
@property (strong, nonatomic) NSMutableDictionary *URLCallbacks;
// This queue is used to serialize the handling of the network responses of all the download operation in a single queue
@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t workingQueue;
@@ -65,9 +67,10 @@ - (id)init
{
if ((self = [super init]))
{
- _downloadQueue = NSOperationQueue.new;
+ _downloadQueue = LIFOOperationQueue.new;
_downloadQueue.maxConcurrentOperationCount = 2;
_URLCallbacks = NSMutableDictionary.new;
+ _operationsDict = NSMutableDictionary.new;
_workingQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloader", DISPATCH_QUEUE_SERIAL);
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
}
@@ -136,6 +139,7 @@ - (NSInteger)maxConcurrentDownloads
[sself callbacksForURL:url];
[sself removeCallbacksForURL:url];
}];
+ [wself.operationsDict setObject:operation forKey:url];
[wself.downloadQueue addOperation:operation];
}];
@@ -175,6 +179,12 @@ - (void)addProgressCallback:(void (^)(NSUInteger, long long))progressBlock andCo
{
createCallback();
}
+ else
+ {
+ // Reprioritize the operation.
+ // LIFOOperationQueue handles this in the addOperation method.
+ [self.downloadQueue addOperation:[self.operationsDict objectForKey:url]];
+ }
});
}
@@ -193,6 +203,7 @@ - (void)removeCallbacksForURL:(NSURL *)url
dispatch_barrier_async(self.barrierQueue, ^
{
[self.URLCallbacks removeObjectForKey:url];
+ [self.operationsDict removeObjectForKey:url];
});
}
Oops, something went wrong.