浏览代码

Modern Objective-C syntax

Bogdan Poplauschi 10 年之前
父节点
当前提交
64382b9

+ 2 - 2
Examples/SDWebImage Demo/AppDelegate.m

@@ -20,10 +20,10 @@
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     //Add a custom read-only cache path
-    NSString *bundledPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CustomPathImages"];
+    NSString *bundledPath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"CustomPathImages"];
     [[SDImageCache sharedImageCache] addReadOnlyCachePath:bundledPath];
 
-    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
+    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
     // Override point for customization after application launch.
 
     MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];

+ 3 - 3
Examples/SDWebImage Demo/MasterViewController.m

@@ -19,7 +19,7 @@
 
 @synthesize detailViewController = _detailViewController;
 
-- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
+- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self)
@@ -90,7 +90,7 @@
 
     cell.textLabel.text = [NSString stringWithFormat:@"Image #%ld", (long)indexPath.row];
     cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
-    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[_objects objectAtIndex:indexPath.row]]
+    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_objects[indexPath.row]]
                       placeholderImage:[UIImage imageNamed:@"placeholder"] options:indexPath.row == 0 ? SDWebImageRefreshCached : 0];
     return cell;
 }
@@ -101,7 +101,7 @@
     {
         self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
     }
-    NSString *largeImageURL = [[_objects objectAtIndex:indexPath.row] stringByReplacingOccurrencesOfString:@"small" withString:@"source"];
+    NSString *largeImageURL = [_objects[indexPath.row] stringByReplacingOccurrencesOfString:@"small" withString:@"source"];
     self.detailViewController.imageURL = [NSURL URLWithString:largeImageURL];
     [self.navigationController pushViewController:self.detailViewController animated:YES];
 }

+ 1 - 1
SDWebImage/NSData+ImageContentType.m

@@ -23,7 +23,7 @@
             return @"image/tiff";
         case 0x52:
             // R as RIFF for WEBP
-            if ([data length] < 12) {
+            if (data.length < 12) {
                 return nil;
             }
 

+ 3 - 2
SDWebImage/SDImageCache.h

@@ -84,7 +84,7 @@ typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger tot
  *
  * @param ns The namespace to use for this cache store
  */
-- (id)initWithNamespace:(NSString *)ns;
+- (instancetype)initWithNamespace:(NSString *)ns;
 
 /**
  * Init a new cache store with a specific namespace and directory
@@ -92,7 +92,8 @@ typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger tot
  * @param ns        The namespace to use for this cache store
  * @param directory Directory to cache disk images in
  */
-- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory;
+- (instancetype)initWithNamespace:(NSString *)ns
+               diskCacheDirectory:(NSString *)directory NS_DESIGNATED_INITIALIZER;
 
 -(NSString *)makeDiskCachePath:(NSString*)fullNamespace;
 

+ 18 - 18
SDWebImage/SDImageCache.m

@@ -42,8 +42,8 @@ static NSData *kPNGSignatureData = nil;
 BOOL ImageDataHasPNGPreffix(NSData *data);
 
 BOOL ImageDataHasPNGPreffix(NSData *data) {
-    NSUInteger pngSignatureLength = [kPNGSignatureData length];
-    if ([data length] >= pngSignatureLength) {
+    NSUInteger pngSignatureLength = kPNGSignatureData.length;
+    if (data.length >= pngSignatureLength) {
         if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
             return YES;
         }
@@ -79,16 +79,16 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
     return instance;
 }
 
-- (id)init {
+- (instancetype)init {
     return [self initWithNamespace:@"default"];
 }
 
-- (id)initWithNamespace:(NSString *)ns {
+- (instancetype)initWithNamespace:(NSString *)ns {
     NSString *path = [self makeDiskCachePath:ns];
     return [self initWithNamespace:ns diskCacheDirectory:path];
 }
 
-- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {
+- (instancetype)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {
     if ((self = [super init])) {
         NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
 
@@ -175,7 +175,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
 #pragma mark SDImageCache (private)
 
 - (NSString *)cachedFileNameForKey:(NSString *)key {
-    const char *str = [key UTF8String];
+    const char *str = key.UTF8String;
     if (str == NULL) {
         str = "";
     }
@@ -183,7 +183,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
     CC_MD5(str, (CC_LONG)strlen(str), r);
     NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                           r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
-                          r[11], r[12], r[13], r[14], r[15], [[key pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [key pathExtension]]];
+                          r[11], r[12], r[13], r[14], r[15], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]];
 
     return filename;
 }
@@ -226,7 +226,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
                 BOOL imageIsPng = hasAlpha;
 
                 // But if we have an image data, we will look at the preffix
-                if ([imageData length] >= [kPNGSignatureData length]) {
+                if (imageData.length >= kPNGSignatureData.length) {
                     imageIsPng = ImageDataHasPNGPreffix(imageData);
                 }
 
@@ -273,7 +273,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
     
     // disable iCloud backup
     if (self.shouldDisableiCloud) {
-        [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
+        [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
     }
 }
 
@@ -287,7 +287,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
     // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
     // checking the key with and without the extension
     if (!exists) {
-        exists = [[NSFileManager defaultManager] fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
+        exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
     }
     
     return exists;
@@ -300,7 +300,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
         // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
         // checking the key with and without the extension
         if (!exists) {
-            exists = [_fileManager fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
+            exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
         }
 
         if (completionBlock) {
@@ -342,7 +342,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
 
     // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
     // checking the key with and without the extension
-    data = [NSData dataWithContentsOfFile:[defaultPath stringByDeletingPathExtension]];
+    data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension];
     if (data) {
         return data;
     }
@@ -357,7 +357,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
 
         // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
         // checking the key with and without the extension
-        imageData = [NSData dataWithContentsOfFile:[filePath stringByDeletingPathExtension]];
+        imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension];
         if (imageData) {
             return imageData;
         }
@@ -544,8 +544,8 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
 
             // Store a reference to this file and account for its total size.
             NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
-            currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
-            [cacheFiles setObject:resourceValues forKey:fileURL];
+            currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
+            cacheFiles[fileURL] = resourceValues;
         }
         
         for (NSURL *fileURL in urlsToDelete) {
@@ -569,7 +569,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
                 if ([_fileManager removeItemAtURL:fileURL error:nil]) {
                     NSDictionary *resourceValues = cacheFiles[fileURL];
                     NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
-                    currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
+                    currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
 
                     if (currentCacheSize < desiredCacheSize) {
                         break;
@@ -622,7 +622,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
     __block NSUInteger count = 0;
     dispatch_sync(self.ioQueue, ^{
         NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
-        count = [[fileEnumerator allObjects] count];
+        count = fileEnumerator.allObjects.count;
     });
     return count;
 }
@@ -642,7 +642,7 @@ FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
         for (NSURL *fileURL in fileEnumerator) {
             NSNumber *fileSize;
             [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
-            totalSize += [fileSize unsignedIntegerValue];
+            totalSize += fileSize.unsignedIntegerValue;
             fileCount += 1;
         }
 

+ 1 - 1
SDWebImage/SDWebImageCompat.m

@@ -17,7 +17,7 @@ inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
         return nil;
     }
     
-    if ([image.images count] > 0) {
+    if ((image.images).count > 0) {
         NSMutableArray *scaledImages = [NSMutableArray array];
 
         for (UIImage *tempImage in image.images) {

+ 2 - 2
SDWebImage/SDWebImageDownloader.m

@@ -60,7 +60,7 @@
     return instance;
 }
 
-- (id)init {
+- (instancetype)init {
     if ((self = [super init])) {
         _operationClass = [SDWebImageDownloaderOperation class];
         _shouldDecompressImages = YES;
@@ -211,7 +211,7 @@
 }
 
 - (void)setSuspended:(BOOL)suspended {
-    [self.downloadQueue setSuspended:suspended];
+    (self.downloadQueue).suspended = suspended;
 }
 
 - (void)cancelAllDownloads {

+ 2 - 2
SDWebImage/SDWebImageDownloaderOperation.h

@@ -64,8 +64,8 @@ extern NSString *const SDWebImageDownloadFinishNotification;
  *
  *  @return the initialized instance
  */
-- (id)initWithRequest:(NSURLRequest *)request
-              options:(SDWebImageDownloaderOptions)options;
+- (instancetype)initWithRequest:(NSURLRequest *)request
+                        options:(SDWebImageDownloaderOptions)options NS_DESIGNATED_INITIALIZER;
 
 /**
  *  Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of

+ 16 - 10
SDWebImage/SDWebImageDownloaderOperation.m

@@ -46,8 +46,14 @@ static NSString *const kCompletedCallbackKey = @"completed";
 @synthesize executing = _executing;
 @synthesize finished = _finished;
 
-- (id)initWithRequest:(NSURLRequest *)request
-              options:(SDWebImageDownloaderOptions)options {
+- (instancetype)init {
+    if (self = [self initWithRequest:nil options:0]) {
+    }
+    return self;
+}
+
+- (instancetype)initWithRequest:(NSURLRequest *)request
+                        options:(SDWebImageDownloaderOptions)options {
     if ((self = [super init])) {
         _request = request;
         _shouldDecompressImages = YES;
@@ -250,7 +256,7 @@ static NSString *const kCompletedCallbackKey = @"completed";
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
     
     //'304 Not Modified' is an exceptional one
-    if (![response respondsToSelector:@selector(statusCode)] || ([((NSHTTPURLResponse *)response) statusCode] < 400 && [((NSHTTPURLResponse *)response) statusCode] != 304)) {
+    if (![response respondsToSelector:@selector(statusCode)] || (((NSHTTPURLResponse *)response).statusCode < 400 && ((NSHTTPURLResponse *)response).statusCode != 304)) {
         NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
         self.expectedSize = expected;
         for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
@@ -264,7 +270,7 @@ static NSString *const kCompletedCallbackKey = @"completed";
         });
     }
     else {
-        NSUInteger code = [((NSHTTPURLResponse *)response) statusCode];
+        NSUInteger code = ((NSHTTPURLResponse *)response).statusCode;
         
         //This is the case when server returns '304 Not Modified'. It means that remote image is not changed.
         //In case of 304 we need just cancel the operation and return cached image from the cache.
@@ -278,7 +284,7 @@ static NSString *const kCompletedCallbackKey = @"completed";
         });
 
         for (SDWebImageDownloaderCompletedBlock completedBlock in [self callbacksForKey:kCompletedCallbackKey]) {
-            completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
+            completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:((NSHTTPURLResponse *)response).statusCode userInfo:nil], YES);
         }
         CFRunLoopStop(CFRunLoopGetCurrent());
         [self done];
@@ -489,17 +495,17 @@ static NSString *const kCompletedCallbackKey = @"completed";
             [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
         } else {
             NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
-            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
+            [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
         }
     } else {
-        if ([challenge previousFailureCount] == 0) {
+        if (challenge.previousFailureCount == 0) {
             if (self.credential) {
-                [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
+                [challenge.sender useCredential:self.credential forAuthenticationChallenge:challenge];
             } else {
-                [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+                [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
             }
         } else {
-            [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+            [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
         }
     }
 }

+ 3 - 3
SDWebImage/SDWebImageManager.m

@@ -28,7 +28,7 @@
 
 @implementation SDWebImageManager
 
-+ (id)sharedManager {
++ (SDWebImageManager*)sharedManager {
     static dispatch_once_t once;
     static id instance;
     dispatch_once(&once, ^{
@@ -37,7 +37,7 @@
     return instance;
 }
 
-- (id)init {
+- (instancetype)init {
     if ((self = [super init])) {
         _imageCache = [self createCache];
         _imageDownloader = [SDWebImageDownloader sharedDownloader];
@@ -56,7 +56,7 @@
         return self.cacheKeyFilter(url);
     }
     else {
-        return [url absoluteString];
+        return url.absoluteString;
     }
 }
 

+ 1 - 1
SDWebImage/SDWebImagePrefetcher.h

@@ -73,7 +73,7 @@ typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls,
 /**
  * Allows you to instantiate a prefetcher with any arbitrary image manager.
  */
-- (id)initWithImageManager:(SDWebImageManager *)manager;
+- (instancetype)initWithImageManager:(SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER;
 
 /**
  * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,

+ 5 - 5
SDWebImage/SDWebImagePrefetcher.m

@@ -32,11 +32,11 @@
     return instance;
 }
 
-- (id)init {
+- (instancetype)init {
     return [self initWithImageManager:[SDWebImageManager new]];
 }
 
-- (id)initWithImageManager:(SDWebImageManager *)manager {
+- (instancetype)initWithImageManager:(SDWebImageManager *)manager {
     if ((self = [super init])) {
         _manager = manager;
         _options = SDWebImageLowPriority;
@@ -63,12 +63,12 @@
 
         if (image) {
             if (self.progressBlock) {
-                self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
+                self.progressBlock(self.finishedCount,(self.prefetchURLs).count);
             }
         }
         else {
             if (self.progressBlock) {
-                self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
+                self.progressBlock(self.finishedCount,(self.prefetchURLs).count);
             }
             // Add last failed
             self.skippedCount++;
@@ -96,7 +96,7 @@
 }
 
 - (void)reportStatus {
-    NSUInteger total = [self.prefetchURLs count];
+    NSUInteger total = (self.prefetchURLs).count;
     if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) {
         [self.delegate imagePrefetcher:self
                didFinishWithTotalCount:(total - self.skippedCount)

+ 2 - 2
SDWebImage/UIImage+GIF.m

@@ -63,13 +63,13 @@
 
     NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
     if (delayTimeUnclampedProp) {
-        frameDuration = [delayTimeUnclampedProp floatValue];
+        frameDuration = delayTimeUnclampedProp.floatValue;
     }
     else {
 
         NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
         if (delayTimeProp) {
-            frameDuration = [delayTimeProp floatValue];
+            frameDuration = delayTimeProp.floatValue;
         }
     }
 

+ 1 - 1
SDWebImage/UIImageView+WebCache.m

@@ -156,7 +156,7 @@ static char TAG_ACTIVITY_SHOW;
 }
 
 - (void)setShowActivityIndicatorView:(BOOL)show{
-    objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, [NSNumber numberWithBool:show], OBJC_ASSOCIATION_RETAIN);
+    objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, @(show), OBJC_ASSOCIATION_RETAIN);
 }
 
 - (BOOL)showActivityIndicatorView{

+ 2 - 2
SDWebImage/UIView+WebCacheOperation.m

@@ -26,13 +26,13 @@ static char loadOperationKey;
 - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key {
     [self sd_cancelImageLoadOperationWithKey:key];
     NSMutableDictionary *operationDictionary = [self operationDictionary];
-    [operationDictionary setObject:operation forKey:key];
+    operationDictionary[key] = operation;
 }
 
 - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
     // Cancel in progress downloader from queue
     NSMutableDictionary *operationDictionary = [self operationDictionary];
-    id operations = [operationDictionary objectForKey:key];
+    id operations = operationDictionary[key];
     if (operations) {
         if ([operations isKindOfClass:[NSArray class]]) {
             for (id <SDWebImageOperation> operation in operations) {