您的位置:首页 > 移动开发 > IOS开发

iOS内存优化常用方法

2016-11-25 17:35 183 查看
1.遇到图片较多且不需要缓存的情况下,不要用imageNamed方法,用initWithContentOfFile加载图片

//加载图片的两种方式
//1.有缓存
UIImage *image = [UIImage imageNamed:@"a.jpg"];

//2.无缓存
NSString *path = [[NSBundle mainBundle] pathForResource:@"a.jpg" ofType:nil];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];

2.UITableView的cell复用:把界面上看不见的cell放入缓存池中,要创建新的cell时先判断缓存池中有无相同identifier可以循环利用的,没有的话再进行创建
//每当有一个cell进入视野范围的时候会调用此方法
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"cellID";
//从缓存池中取出可以循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:ID];
}

return cell;

}

3.打包发布时去掉所有的NSLog:NSLog打印比较耗费性能,特别是打印字符串的拼接,解决方法可以在pch文件中定义一个宏来替换NSLog,用自己定义的log函数,等到发布之前将自己的定义注释掉
#ifdef DEBUG          //如果是调试状态
#define HITLog(...)   NSLog(__VA_ARGS__)       //把NSLog换成自己写的HITLog
#else                 //如果是发布状态
#define HITLog(...)   //把自己写的HITLog定义成空
#endif</span></span>
//除了自己定义Log函数,还可以把常用的数据抽成宏放在pch文件中,省的每个文件都要定义宏
#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

#define iPhone5 ([UIScreen mainScreen].bounds.size.height == 568)
#define iPhone6 ([UIScreen mainScreen].bounds.size.height == 667)
#define iPhone6Plus ([UIScreen mainScreen].bounds.size.height == 736)</span>
4.不要让主线程承担大量的数据处理任务:可以把比较费时的加载图片等任务放到子线程中来做,做好之后在主线程中更新UI界面,iOS中的三种多线程方法NSThread、GCD、NSOperation;详细内容请参考http://blog.csdn.net/xgcyangguang/article/details/51240379


5.当创建了大量的临时对象时,最好加入autorelesaepool保证对象及时的释放
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: