UIImage应用的内存使用情况对比

该博客探讨了在iOS应用中,通过`imageNamed:`、`imageWithContentsOfFile:`和`imageWithData:`三种方式加载UIImage时的内存使用情况。在代码示例中,展示了如何循环加载不同数量的图片,并通过比较不同加载方法对内存的影响,揭示了最佳实践。
摘要由CSDN通过智能技术生成
新建一个项目,只写一个界面


设备: 模拟器(5.1)

工具:instrument 中的 Allocations

数据Allocations:All Allocations


image:共121张 (把图片名字改为: 2…n.png)

测试代码

- (void)viewDidLoad

{

    [super viewDidLoad];

    for (int j = 0; j < 1; j ++) {

        for (int i = 2; i <= 122; i ++) {

            //named

            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]];

            

            //bundle

            UIImage *image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",i]]];

            

            //data

            NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d",i] ofType:@"png"];

            NSData *imageData = [NSData dataWithContentsOfFile:filePath];

            UIImage *image = [UIImage imageWithData:imageData];

            

            if (image) 

            {

                UIImageView *imageView = [[UIImageView alloc] initWithImage:image];    

                imageView.frame = CGRectMake(0, 10*i, 50, 50);

                [self.view addSubview:imageView];

                [imageView release];

            }

        }

    }

}



All Allocations数据对比(测试时注视掉相应代码,运行30S时的数据)



                    named                    bundle                        data
——————————————————————————————
j = 0                                             846kb
———————————————————————————— ——
j = 1              1.20 M                    1.16 M                        1.36 M
———————————————————————————— ——
j = 2               1.23 M                    1.50 M                        1.90 M 
———————————————————————————— ——
j = 4              1.29 M                    2.18 M                        2.97 M
———————————————————————————— ——
j = 6               1.36 M                    2.86 M                        4.06 M
———————————————————————————— ——
j =10              1.48 M                   4.20 M                        6.19 M
———————————————————————————— ——




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值