字符串转化成NSURL类型后为nil

NSString *dateStr=[dic objectForKey:@"date"];// 2014-01-01 11:23:23
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
 NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromdate=[format dateFromString:dateStr];
NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
 NSLog(@"fromdate=%@",fromDate);
[format release];
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
NSLog(@"enddate=%@",localeDate);
NSDateComponents *components = [gregorian components:unitFlags fromDate:fromDate toDate:localeDate options:0]; 
NSInteger months = [components month]; 
NSInteger days = [components day];//年[components year]
NSLog(@"month=%d",months);
NSLog(@"days=%d",days);
[gregorian release];
if (months==0&&days;==0) {
    dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
    cell.textLabel.text=[NSString stringWithFormat:@"今天 %@",dateStr];//今天 11:23
}else if(months==0&&days;==1){
    dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
    cell.textLabel.text=[NSString stringWithFormat:@"昨天 %@",dateStr];//昨天 11:23
}else{
    dateStr=[dateStr substringToIndex:10];
    cell.textLabel.text=dateStr;
}
//该片段来自于http://outofmemory.cn
  • 只要字符串中涵盖中文,可能导致转化成NSURL之后吧nil。
    解决办法:

manbetx手机网页版,//注:转义字符或字符串中寓粤语, 都可能引致url=nil
NSString * urlStr = @” “; //含有闽南语的字符串
NSString * urlStr1 = [strUrl
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr1];

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图