Sorting by date format in iphone

喜欢而已 提交于 2019-12-12 01:33:50

问题


I am new to iphone development.I am sorting a mutable array with respect to date.But it is sorting Using the date parameter consider it as string.I want to sort it by date.How can i achieve that .Please help me out.

 NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"pubDate" ascending:YES];
[stories sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

Can i use selectors? if so how should i use it?.Thanks.


回答1:


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{ 
    [dateString appendString:string];
}    

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{  
  NSDateFormatter *df = [[[NSDateFormatter alloc] init]autorelease];
  [df setDateFormat:@"dd.MM.yyyy"]; //change the format if you are using it in different way
  NSDate *myDate = [df dateFromString: dateString];
  [dateArray addObject:myDate];
}

after that you can sort the array just using the way you wrote in question.




回答2:


Is the pubDate property of the objects in your array NSStrings or NSDates? I use that exact code on an array of objects with NSDates and it works perfectly fine. If you're using NSStrings you'll want to first convert them to date objects so you can properly sort by date.



来源:https://stackoverflow.com/questions/2302627/sorting-by-date-format-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!