【问题标题】:Overriding initWithImage for an UIImageView inside a NIB为 NIB 中的 UIImageView 覆盖 initWithImage
【发布时间】:2012-06-29 05:49:40
【问题描述】:

这里是交易:我的故事板中有 25 个视图控制器,每个都有一个 UIImageView,它显示一个大文件大小的 PNG。

事实证明,nib 中的 UIImageView 将使用 [UIImageView initWithImage:[UIImage imageNamed:]] 方法 (see the docs) 加载其图像。使用imageNamed: 的问题在于,当每个视图控制器被加载时,其 UIImageView 中的图像被放置在缓存中,并且我的应用程序很快开始收到内存警告和崩溃。

出路是使用[UIImageView initWithImage:[UIImage imageWithContentsOfFile:]],它会加载图像但不缓存它。所以我要做的是使用在我的NIB 文件中 调用imageWithContentsOfFile 的UIImageView 的子类。但我不知道如何获取在 Interface Builder 的 Attributes Inspector 中设置的图像文件的名称。

UIImageViewNoCache.h

#import <UIKit/UIKit.h>

@interface UIImageViewNoCache : UIImageView
@end

UIImageViewNoCache.h

#import "UIImageViewNoCache.h"

@implementation UIImageViewNoCache

-(id)initWithImage:(UIImage *)image{
   self = [super init];
    if(self){
        self.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], theNameOfTheImageInTheNib];]
    }
}
@end

那么,我怎样才能得到theNameOfTheImageInTheNib

【问题讨论】:

  • 我认为图像缓存不会像您认为的那样......缓存它会减少图像在多次使用时的内存
  • @JustinMeiners:不,它确实增加了内存大小,请阅读此处:stackoverflow.com/questions/289360/…
  • 在那个问题中,我理解问题是图像使用的内存永远不会被释放,而不是让图像缓存的行为进行了复制或其他操作
  • 您也无法获取图像的名称,因为图像不存储与其名称或文件名相关的信息,因为它们可以在代码等中创建,如果调用 initWithImage 也不会那样传入方法的图像是否已经在缓存中?

标签: ios uiimageview uistoryboard


【解决方案1】:

看看我写的这个类别:UIImage+SDSCache

它会调动imageNamed,所以不要使用缓存。它可能对您有用,或者作为如何解决您的特定问题的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多