@@ -122,4 +122,47 @@ + (UIImage *)as_resizableRoundedImageWithCornerRadius:(CGFloat)cornerRadius
122122 return result;
123123}
124124
125+ #pragma mark - as_imageNamed
126+
127+ UIImage *cachedImageNamed (NSString *imageName, UITraitCollection *traitCollection)
128+ {
129+ static NSCache *imageCache = nil ;
130+ static dispatch_once_t onceToken;
131+ dispatch_once (&onceToken, ^{
132+ // Because NSCache responds to memory warnings, we do not need an explicit limit.
133+ // all of these objects contain compressed image data and are relatively small
134+ // compared to the backing stores of text and image views.
135+ imageCache = [[NSCache alloc ] init ];
136+ });
137+
138+ UIImage *image = nil ;
139+ if ([imageName length ] > 0 ) {
140+ NSString *imageKey = imageName;
141+ if (traitCollection) {
142+ char imageKeyBuffer[256 ];
143+ snprintf (imageKeyBuffer, sizeof (imageKeyBuffer), " %s |%ld |%ld " , imageName.UTF8String , (long )traitCollection.horizontalSizeClass , (long )traitCollection.verticalSizeClass );
144+ imageKey = [NSString stringWithUTF8String: imageKeyBuffer];
145+ }
146+
147+ image = [imageCache objectForKey: imageKey];
148+ if (!image) {
149+ image = [UIImage imageNamed: imageName inBundle: nil compatibleWithTraitCollection: traitCollection];
150+ if (image) {
151+ [imageCache setObject: image forKey: imageKey];
152+ }
153+ }
154+ }
155+ return image;
156+ }
157+
158+ + (UIImage *)as_imageNamed : (NSString *)imageName
159+ {
160+ return cachedImageNamed (imageName, nil );
161+ }
162+
163+ + (UIImage *)as_imageNamed : (NSString *)imageName compatibleWithTraitCollection : (UITraitCollection *)traitCollection
164+ {
165+ return cachedImageNamed (imageName, traitCollection);
166+ }
167+
125168@end
0 commit comments