forked from jakemarsh/JMImageCache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIImageView+JMImageCache.m
87 lines (65 loc) · 2.54 KB
/
UIImageView+JMImageCache.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
// UIImageView+JMImageCache.m
// JMImageCacheDemo
//
// Created by Jake Marsh on 7/23/12.
// Copyright (c) 2012 Jake Marsh. All rights reserved.
//
#import "UIImageView+JMImageCache.h"
#import "JMImageCache.h"
#import <objc/runtime.h>
static char kJMImageURLObjectKey;
@interface UIImageView (_JMImageCache)
@property (readwrite, nonatomic, retain, setter = jm_setImageURL:) NSURL *jm_imageURL;
@end
@implementation UIImageView (_JMImageCache)
@dynamic jm_imageURL;
@end
@implementation UIImageView (JMImageCache)
#pragma mark - Private Setters
- (NSURL *) jm_imageURL {
return (NSURL *)objc_getAssociatedObject(self, &kJMImageURLObjectKey);
}
- (void) jm_setImageURL:(NSURL *)imageURL {
objc_setAssociatedObject(self, &kJMImageURLObjectKey, imageURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark - Public Methods
- (void) setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholder:nil];
}
- (void) setImageWithURL:(NSURL *)url placeholder:(UIImage *)placeholderImage {
[self setImageWithURL:url key:nil placeholder:placeholderImage];
}
- (void) setImageWithURL:(NSURL *)url placeholder:(UIImage *)placeholderImage completion:(void (^)(UIImage *))completion {
[self setImageWithURL:url key:nil placeholder:placeholderImage completion:completion];
}
- (void) setImageWithURL:(NSURL *)url key:(NSString*)key placeholder:(UIImage *)placeholderImage {
[self setImageWithURL:url key:key placeholder:placeholderImage completion:nil];
}
- (void)setImageWithURL:(NSURL *)url key:(NSString*)key placeholder:(UIImage *)placeholderImage completion:(void (^)(UIImage *image))completion {
self.jm_imageURL = url;
// If the imageView didn't had an image, we set the placeholder image
if (!self.image && placeholderImage) {
self.image = placeholderImage;
[self setNeedsDisplay];
[self setNeedsLayout];
}
// Completion block executed after the fetch
__weak UIImageView *safeSelf = self;
void (^imageCompletionBlock)(UIImage *) = ^(UIImage *image) {
if(image) {
safeSelf.image = image;
[safeSelf setNeedsLayout];
[safeSelf setNeedsDisplay];
}
safeSelf.jm_imageURL = nil;
if (completion) completion(image);
};
// Get image from cache (execute in background if using disk or network)
if (key) {
[[JMImageCache sharedCache] imageForURL:url key:key completionBlock:imageCompletionBlock];
} else {
[[JMImageCache sharedCache] imageForURL:url completionBlock:imageCompletionBlock];
}
}
@end