-(id) init {
self = [super init];
if (self) {
CGRect rect_screen = [[UIScreen mainScreen]bounds];
CGSize size_screen = rect_screen.size;
CGFloat scale_screen = [UIScreen mainScreen].scale;
size_screen.width *= scale_screen;
size_screen.height *= scale_screen;
if ( CGSizeEqualToSize(size_screen, CGSizeMake(320, 480))
|| CGSizeEqualToSize(size_screen, CGSizeMake(480, 320))
|| CGSizeEqualToSize(size_screen, CGSizeMake(1024, 768))
|| CGSizeEqualToSize(size_screen, CGSizeMake(768, 1024))) {
isRetain = NO;
} else {
isRetain = YES;
}
imageDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
[self performSelector:@selector(runPerTimes) withObject:nil afterDelay:KAutoReleaseTime]; // 60 秒后释放缓存
}
return self;
}
-(void) dealloc{
if (imageDictionary) {
[imageDictionary release];
imageDictionary = nil;
}
[super dealloc];
}
- (UIImage *)imageNamed:(NSString *)name{
NSMutableString* temp = [[NSMutableString alloc] initWithString:name];
NSRange range = [temp rangeOfString:@"@2x"];
if (range.length > 0 && !isRetain) {//低分辨率下有@2x
[temp deleteCharactersInRange:range];
} else if(range.length == 0 && isRetain){//高分辨率下无@2x
range = [temp rangeOfString:@"."];
if (range.length == 0) {
[temp appendString:@"@2x"];
} else {
[temp insertString:@"@2x" atIndex:range.location];
}
}
range = [temp rangeOfString:@"."];//没有后缀
if (range.length == 0) {
[temp appendString:@".png"];
}
UIImage* image = [imageDictionary objectForKey:temp];
if (image == nil) {
NSString *path = [NSString stringWithFormat:@"%@/%@",
[[NSBundle mainBundle] bundlePath],
temp];
image = [[UIImage alloc] initWithContentsOfFile:path];
if (image) {
[imageDictionary setObject:image forKey:temp];
[image release];
}
}
[temp release];
return image;
}
-(void) runPerTimes{
[self releaseNotUsedImages];
[self performSelector:@selector(runPerTimes) withObject:nil afterDelay:KAutoReleaseTime];
}
- (void) releaseNotUsedImages{
NSArray* array = [imageDictionary allKeys];
for (int i = 0; i < [array count]; i++) {
NSString* name = [array objectAtIndex:i];
UIImage* image = [imageDictionary objectForKey:name];
if (image.retainCount <= 1) {
[imageDictionary removeObjectForKey:name];
}
}
}