UIImage imageNamed:误区

本文讨论了在大量加载图片的程序中,直接使用UIImageimageNamed:方法的潜在问题,强调了采用NSString和imageWithContentsOfFile:方法进行图片加载的重要性。重点解释了这种方法如何避免内存泄露,提供了一种更安全、更有效的图片资源管理策略。

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

如题,是不是大家为了方便都这样加载图片啊

myImage = [UIImage imageNamed:@"icon.png"];
那么小心了
这种方法在一些图片很少,或者图片很小的程序里是ok的。
但是,在大量加载图片的程序里,请千万不要这样做。
为什么呢 ???????
这种方法在application bundle的顶层文件夹寻找由供应的名字的图象 。 如果找到图片,装载到iPhone系统缓存图象。那意味图片是(理论上)放在内存里作为cache的。
试想你图片多了,是什么后果``````
图片cache极有可能不会响应 memory warnings and release its objects
所以,用图片的时候一定要小心的alloc和release
推荐使用
NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];

myImage = [UIImage imageWithContentsOfFile:path];

转载于:https://www.cnblogs.com/yilia/p/3433650.html

/ // 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、付费专栏及课程。

余额充值