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

iOS优化之路

2015-07-30 23:59 471 查看
持续更新。。。

一,所有的对象创建都需要一定的时间,所以在创建对象的时候,能够复用就不要继续alloc创建对象,举例:

-(NSString *)dateStringFromDate:(NSDate *)now{
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.dateStyle = kCFDateFormatterShortStyle;
fmt.timeStyle = kCFDateFormatterShortStyle;
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString* dateString = [fmt stringFromDate:now];
return dateString;
}


上面这段代码中主要是

NSDateFormatter* fmt = [[NSDateFormatteralloc]init];
这句代码创建NSDateFormatter 对象耗费时间太多,如果有很多对象都调用这个方法的话就会创建很多个 NSDateFormatter 对象,这样耗费的时间就会很多了,如果是异步返回结果还好,如果是同步返回结果的话,就会阻塞UI,界面不流畅,所以可以这样改:

-(NSString *)dateStringFromDate:(NSDate *)now{

static NSDateFormatter* fmt;
if(fmt==nil){
fmt = [[NSDateFormatter alloc] init];
}
fmt.dateStyle = kCFDateFormatterShortStyle;
fmt.timeStyle = kCFDateFormatterShortStyle;
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString* dateString = [fmt stringFromDate:now];
return dateString;
}
这样的好处是,只创建一个对象,如果下一个对象要调用这个方法的话,省去了创建 NSDateFormatter 对象的时间,所以会有很明显的效果

或者可以这样优化:
+ (NSString *)stringFromDate:(NSDate *)date andFormat:(NSString *)format withTimeZone:(NSTimeZone *)timeZone
{
if (! date) {
date = [NSDate date];
}
if (! format) {
format = @"yyyyMMdd HH:mm:ss";
}

NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
NSMutableDictionary *dateFormatters = nil;

@synchronized(threadDict)
{
dateFormatters = threadDict[@"dateFormatters"];
if(dateFormatters == nil)
{
dateFormatters = [NSMutableDictionary dictionary];
threadDict[@"dateFormatters"] = dateFormatters;
}
}

NSDateFormatter *formatter = dateFormatters[format];
if(formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone systemTimeZone];
if([timeZone isKindOfClass:[NSTimeZone class]])
{
formatter.timeZone = timeZone;
}

formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
formatter.dateFormat = format;
dateFormatters[format] = formatter;
}

return [formatter stringFromDate:date];
}


每次获取当前线程的 NSDateFormatter 对象,没有就存起来,这样线程之间就不会相互干扰了,同时也到达了复用 NSDateFormatter 对象的目的。

二、tableveiw 的cell 过长时,如果对cell设置渲染效果,会消耗非常大的内存,(麻蛋,查了一天终于找到元凶了)。举例:
当你的单个cell高度达到10000时,开启cell的默认点击渲染效果cell.selectionStyle =UITableViewCellSelectionStyleDefault,会产生一个额外的内存消耗,大概会有多出200M左右的一个峰值,是不是很恐怖!具体原因可能是UIKit内部设计的问题了。
目前的解决方案就是把这个点击渲染效果去掉了 cell.selectionStyle =UITableViewCellSelectionStyleNone 。没办法,渲染效果和性能只能选其一了。。。

待续。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: