我希望得到以下结果:
set arr [0] = jan23,2016 ...... upto arr [6] = jan29,2016。
为此,我有以下代码:
// To get future or next 6 days from now or current date
NSCalendar * calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents * datecomponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:[NSDate date]];
for(int i=0;i<6;++i)
{
NSDate * todaydate = [calendar dateFromComponents:datecomponents];
NSLog(@"%@",todaydate);
++datecomponents.day;
NSDateFormatter * dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterMediumStyle];
NSString * convertedstring = [dateformatter stringFromDate:todaydate];
NSLog(@“converteddate:%@",convertedstring);
为此,我收到了如下回复:
convertdate:2016年1月23日,类似于jan29,2016
然后我喜欢这个:
NSMutableString * newstring = [[NSMutableString alloc]init];
[newstring stringByAppendingString:convertedstring];
NSLog(@"%@",newstring);
也是这样:
NSMutableArray * arrdata;
arrdata = [[NSMutableArray alloc]init];
[arrdata addObject:convertedstring];
NSLog(@"%@",arrdata);
}
如何获得上述结果集。在字符串迭代之后如何将它们转换为数组。
答案 0 :(得分:1)
在每次迭代重置时,必须在for
循环之外声明和分配数组:
NSMutableArray * arrdata = [[NSMutableArray alloc]init];
NSCalendar * calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents * datecomponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:[NSDate date]];
for(int i=0;i<6;++i)
也没有必要这样做,因为你从来没有真正使用newstring
:
NSMutableString * newstring = [[NSMutableString alloc]init];
[newstring stringByAppendingString:convertedstring];
答案 1 :(得分:0)
以下是完整的答案:
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *datecomponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:[NSDate date]];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterMediumStyle];
NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int i = 0; i < 6; i++)
{
NSDate * todaydate = [calendar dateFromComponents:datecomponents];
NSLog(@"%@",todaydate);
++datecomponents.day;
NSString *convertedstring = [dateformatter stringFromDate:todaydate];
[arr addObject:convertedstring];
}
希望这有帮助!