UIImage 的imageNamed内存泄露的解决方法

本文探讨了在iOS开发中使用UIImage加载图片时如何通过条件判断选择合适的加载方式,以减少内存消耗并避免内存泄露问题,特别是针对大量图片加载场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   UIImage 加载图片使用“[UIImage imageNamed:@"xxx.png"]时,系统会把图像Cache到内存。如果图像比较大,或者图像比较多,用这种方式会消耗很大的内存,而且释放图像的内存是一件相对来说比较麻烦的事情。例如:如果利用imageNamed的方式加载图像到一个动态数组,然后将将数组赋予一个UIView的对象的进行逐帧动画,那么这将会很有可能造成内存泄露。解决上述问题的最佳方法是:

if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0) {
	[UIImage initWithCGImage:[[UIImage imageWithData:[NSData dataWithContentsOfFile:@"xxx@2x.png"]] CGImage] scale:2.0 orientation:UIImageOrientationUp];
} else {
	[UIImage imageWithContentsOfFile:@"xxx.png"];
}


转载于:https://my.oschina.net/chengliqun/blog/113792

/ // HBBaseTabbarViewController.m // wechat // // Created by josh on 2025/3/21. // #import "HBBaseTabbarViewController.h" #import "HBCustomTabBar.h" #import "HBFriendLineViewController.h" #import "HBProfileViewController.h" #import "HBHomeViewController.h" #import "HBContactViewController.h" @interface HBBaseTabbarViewController () @end @implementation HBBaseTabbarViewController - (void)viewDidLoad { [super viewDidLoad]; // 替换默认的 TabBar [self setValue:[[HBCustomTabbar alloc] init] forKey:@"tabBar"]; // 设置子视图控制器 [self setupViewControllers]; } - (void)setupViewControllers { // 创建 4 个子视图控制器 HBHomeViewController *homeVC = [[HBHomeViewController alloc] init]; // homeVC.view.backgroundColor = [UIColor whiteColor]; homeVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"home"] selectedImage:[UIImage imageNamed:@"home-sel"]]; HBContactViewController *contactVC = [[HBContactViewController alloc] init]; // contactVC.view.backgroundColor = [UIColor whiteColor]; contactVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"通讯录" image:[UIImage imageNamed:@"contact"] selectedImage:[UIImage imageNamed:@"tongxunlu-sel"]]; HBFriendLineViewController *frienVC = [[HBFriendLineViewController alloc] init]; frienVC.view.backgroundColor = [UIColor whiteColor]; frienVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"朋友圈" image:[UIImage imageNamed:@"pengyouquan"] selectedImage:[UIImage imageNamed:@"pengyouquan-sel"]]; HBProfileViewController *profileVC = [[HBProfileViewController alloc] init]; profileVC.view.backgroundColor = [UIColor whiteColor]; profileVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"me"] selectedImage:[UIImage imageNamed:@"me-sel"]]; // 将子视图控制器添加到 TabBarController self.viewControllers = @[homeVC, contactVC, frienVC, profileVC]; } 这一串代码的作用
03-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值