我有一个NSCache实例,比如:NSCache *imageCache; --它主要用于保存一些具有不同"@keys"的远程“映像”值。I alloc & init NSCache在全局类的开头,并设置一个if else条件,如下所示:
if (self.imageCache == nil)
{
self.imageCache = [[NSCache alloc] init];
}
else
{
NSLog(@"cache set");
}我#import所有ViewControllers中的“全局类”,这样我就不必每次解析图像了。但问题是,当我每次去其他ViewControllers时,似乎都是NSCache alloc & init。因为加载图像需要与1stVC相同的时间。我认为if else条件不能很好地工作,或者这不是检查NSCache集的适当方法。有人能告诉我它有什么问题吗?此外,imageCache是从全局变量中使用的。
提前谢谢。
祝你今天愉快。
加法:
这是我在UIScrollView中以subView的形式加载subView的方法。这是一个UIViewClass,我在"EveryViewController“中添加了一个subView,请看一下if (cachedImage)行。效果很好。但是,当我想检查NSCache (iADImageCache)集或不检查时,它会显示它没有设置。但这是应该设定的。在这种情况下,如何使用不同的iADImageCache名称检查所有的@"Key"?再次感谢。
-(void) loadUIButton
{
[self loadScrollView];
for (int i = 0; i < [iADDisplayArray count]; i++)
{
adButtonOutLet = [[UIButton alloc] initWithFrame:CGRectMake(i*320, 0, ButtonWidth, ButtonHight)];
currentAd = [iADDisplayArray objectAtIndex:i];
NSString *path = currentAd.bannerIconURL;
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *requestWithBodyParams = [NSMutableURLRequest requestWithURL:url];
NSData *imageData = [NSURLConnection sendSynchronousRequest:requestWithBodyParams returningResponse:nil error:nil];
UIImage *originalImage = [UIImage imageWithData:imageData];
UIImage *cachedImage = [self.iADImageCache objectForKey:currentAd.bannerIconURL];
if (cachedImage)
{
[adButtonOutLet setImage:cachedImage forState:UIControlStateNormal];
//NSLog(@"OnecachedImage %@", cachedImage);
}
else
{
[self.iADImageCache setObject:originalImage forKey:currentAd.bannerIconURL];
[adButtonOutLet setImage:originalImage forState:UIControlStateNormal];
NSLog(@"OneimageCache %@", self.iADImageCache);
}
adButtonOutLet.userInteractionEnabled= YES;
[adButtonOutLet setTag:i];
[adButtonOutLet addTarget:self action:@selector(goToURL:) forControlEvents:UIControlEventTouchUpInside];
[self.iADScrollView addSubview:adButtonOutLet];
}
}发布于 2014-09-10 10:58:13
您可以创建一个单例类,应用程序中的实例通过所有视图控制器完成启动并在任何地方使用它。在单例类中,放置一个属性
@property(nonatomic,strong) NSCache* imageCache;然后在singleton类init方法中只执行一次。通过这种方式,您不必关心它,只需将图像添加到缓存中即可。当然,您必须根据缓存中是否存在一个键来检查图像是否被缓存。
NSCache* globalCache = [SingletonClass sharedInstanceMethod].imageCache;
UIImage *imageX = [globalCache objectForKey: @"keyX"];
if (!imageX) {
// download your image
imageX = <Download method>;
[globalCache setObject: imageX forKey: @"keyX"];
}
// Do your stuff (like showing the image)
....
...
..
.希望它能帮上忙
发布于 2016-04-28 10:32:38
除非整个程序实际需要,否则我建议另一种方法,通过添加类方法,将缓存限制在实际需要使用缓存的类上:
+ (NSCache *)staticCacheForClass
{
static NSCache *staticCache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
staticCache = [NSCache new];
staticCache.name = @"myCache";
});
return staticCache;
}使用此方法--将缓存的更改限制为使用缓存的类的内部更改,并避免创建另一个单例。在创建和销毁该类的实例时,缓存也会被保存。
也就是说,如果需要从不同的类访问缓存,那么单例可能是一个可行的解决方案,因为缓存单例并不是真正的全局状态。
干杯。
https://stackoverflow.com/questions/25762129
复制相似问题