Skip to content

Commit

Permalink
Modern Objective-C syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
bpoplauschi committed May 23, 2016
1 parent 8a78586 commit 64382b9
Show file tree
Hide file tree
Showing 15 changed files with 62 additions and 55 deletions.
4 changes: 2 additions & 2 deletions Examples/SDWebImage Demo/AppDelegate.m
Expand Up @@ -20,10 +20,10 @@ @implementation AppDelegate
- (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];
Expand Down
6 changes: 3 additions & 3 deletions Examples/SDWebImage Demo/MasterViewController.m
Expand Up @@ -19,7 +19,7 @@ @implementation MasterViewController

@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)
Expand Down Expand Up @@ -90,7 +90,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N

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;
}
Expand All @@ -101,7 +101,7 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
{
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];
}
Expand Down
2 changes: 1 addition & 1 deletion SDWebImage/NSData+ImageContentType.m
Expand Up @@ -23,7 +23,7 @@ + (NSString *)sd_contentTypeForImageData:(NSData *)data {
return @"image/tiff";
case 0x52:
// R as RIFF for WEBP
if ([data length] < 12) {
if (data.length < 12) {
return nil;
}

Expand Down
5 changes: 3 additions & 2 deletions SDWebImage/SDImageCache.h
Expand Up @@ -84,15 +84,16 @@ 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
*
* @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;

Expand Down
36 changes: 18 additions & 18 deletions SDWebImage/SDImageCache.m
Expand Up @@ -42,8 +42,8 @@ - (void)dealloc
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;
}
Expand Down Expand Up @@ -79,16 +79,16 @@ + (SDImageCache *)sharedImageCache {
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];

Expand Down Expand Up @@ -175,15 +175,15 @@ - (NSString *)defaultCachePathForKey:(NSString *)key {
#pragma mark SDImageCache (private)

- (NSString *)cachedFileNameForKey:(NSString *)key {
const char *str = [key UTF8String];
const char *str = key.UTF8String;
if (str == NULL) {
str = "";
}
unsigned char r[CC_MD5_DIGEST_LENGTH];
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;
}
Expand Down Expand Up @@ -226,7 +226,7 @@ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate 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);
}

Expand Down Expand Up @@ -273,7 +273,7 @@ - (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key {

// disable iCloud backup
if (self.shouldDisableiCloud) {
[fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
[fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}

Expand All @@ -287,7 +287,7 @@ - (BOOL)diskImageExistsWithKey:(NSString *)key {
// 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;
Expand All @@ -300,7 +300,7 @@ - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheC
// 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) {
Expand Down Expand Up @@ -342,7 +342,7 @@ - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {

// 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;
}
Expand All @@ -357,7 +357,7 @@ - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {

// 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;
}
Expand Down Expand Up @@ -544,8 +544,8 @@ - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {

// 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) {
Expand All @@ -569,7 +569,7 @@ - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
if ([_fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;

if (currentCacheSize < desiredCacheSize) {
break;
Expand Down Expand Up @@ -622,7 +622,7 @@ - (NSUInteger)getDiskCount {
__block NSUInteger count = 0;
dispatch_sync(self.ioQueue, ^{
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
count = [[fileEnumerator allObjects] count];
count = fileEnumerator.allObjects.count;
});
return count;
}
Expand All @@ -642,7 +642,7 @@ - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completio
for (NSURL *fileURL in fileEnumerator) {
NSNumber *fileSize;
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
totalSize += [fileSize unsignedIntegerValue];
totalSize += fileSize.unsignedIntegerValue;
fileCount += 1;
}

Expand Down
2 changes: 1 addition & 1 deletion SDWebImage/SDWebImageCompat.m
Expand Up @@ -17,7 +17,7 @@
return nil;
}

if ([image.images count] > 0) {
if ((image.images).count > 0) {
NSMutableArray *scaledImages = [NSMutableArray array];

for (UIImage *tempImage in image.images) {
Expand Down
4 changes: 2 additions & 2 deletions SDWebImage/SDWebImageDownloader.m
Expand Up @@ -60,7 +60,7 @@ + (SDWebImageDownloader *)sharedDownloader {
return instance;
}

- (id)init {
- (instancetype)init {
if ((self = [super init])) {
_operationClass = [SDWebImageDownloaderOperation class];
_shouldDecompressImages = YES;
Expand Down Expand Up @@ -211,7 +211,7 @@ - (SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBl
}

- (void)setSuspended:(BOOL)suspended {
[self.downloadQueue setSuspended:suspended];
(self.downloadQueue).suspended = suspended;
}

- (void)cancelAllDownloads {
Expand Down
4 changes: 2 additions & 2 deletions SDWebImage/SDWebImageDownloaderOperation.h
Expand Up @@ -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
Expand Down
26 changes: 16 additions & 10 deletions SDWebImage/SDWebImageDownloaderOperation.m
Expand Up @@ -46,8 +46,14 @@ @implementation SDWebImageDownloaderOperation {
@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;
Expand Down Expand Up @@ -250,7 +256,7 @@ - (BOOL)isConcurrent {
- (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]) {
Expand All @@ -264,7 +270,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLRespon
});
}
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.
Expand All @@ -278,7 +284,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLRespon
});

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];
Expand Down Expand Up @@ -489,17 +495,17 @@ - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticatio
[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];
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions SDWebImage/SDWebImageManager.m
Expand Up @@ -28,7 +28,7 @@ @interface SDWebImageManager ()

@implementation SDWebImageManager

+ (id)sharedManager {
+ (SDWebImageManager*)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
Expand All @@ -37,7 +37,7 @@ + (id)sharedManager {
return instance;
}

- (id)init {
- (instancetype)init {
if ((self = [super init])) {
_imageCache = [self createCache];
_imageDownloader = [SDWebImageDownloader sharedDownloader];
Expand All @@ -56,7 +56,7 @@ - (NSString *)cacheKeyForURL:(NSURL *)url {
return self.cacheKeyFilter(url);
}
else {
return [url absoluteString];
return url.absoluteString;
}
}

Expand Down
2 changes: 1 addition & 1 deletion SDWebImage/SDWebImagePrefetcher.h
Expand Up @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions SDWebImage/SDWebImagePrefetcher.m
Expand Up @@ -32,11 +32,11 @@ + (SDWebImagePrefetcher *)sharedImagePrefetcher {
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;
Expand All @@ -63,12 +63,12 @@ - (void)startPrefetchingAtIndex:(NSUInteger)index {

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++;
Expand Down Expand Up @@ -96,7 +96,7 @@ - (void)startPrefetchingAtIndex:(NSUInteger)index {
}

- (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)
Expand Down

0 comments on commit 64382b9

Please sign in to comment.