2

我在 NSDate 格式的 NSArray 中有一组非连续日期。我需要在数组中使用相同的日期集,但在格式为 dd/MM 的 NSString 中。我想我需要循环读取原始数组中的每个日期,将其转换为字符串并根据需要对其进行格式化,但我不知道如何逐步遍历原始数组。

NSError *error2;
NSArray *swim750mArray = [context executeFetchRequest:request2 error:&error2];
if (swim750mArray == nil) {
    NSLog(@"The fetch request2 returned an array == nil");
} else {
    NSLog(@"The fetch request2 returned an array...");
    NSLog(@"%@", swim750mArray);

NSArray *datesAsDates = [swim750mArray valueForKey:@"date"];
NSMutableArray* arrayOfDatesAsStrings = [NSMutableArray arrayWithCapacity:count];

    //SomeCode - Convert the Array of NSDates to a new Array of dates as NSStrings...

      for (int i=0; i<index; i++) {
           //get the date next NSDate from the array as: NSDate *dateAsDate...
           NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
           [dateFormat setDateFormat:@"dd/MM"];


         NSString *dateAsStr = [dateFormat stringFromDate:dateAsDate];

         [arrayOfDatesAsStrings addObject:dateAsStr];
        }

这个答案与我需要的很接近,只是它没有从现有数组中读取:How to use NSDate formatter with a array of dates?

请帮忙!提前谢谢了...

4

2 回答 2

4

使用快速枚举怎么样?

for (NSDate* dateAsDate in datesAsDates) {
     //get the date next NSDate from the array as: NSDate *dateAsDate...
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
     [dateFormat setDateFormat:@"dd/MM"];

     NSString *dateAsStr = [dateFormat stringFromDate:dateAsDate];

     [arrayOfDatesAsStrings addObject:dateAsStr];
}
于 2012-11-02T18:54:56.223 回答
1

jere 命名为快速枚举。它也可以通过基于块的枚举来完成。此外,您应该创建一次格式化程序并重新使用它

NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"dd/MM"];

NSMutableArray *datesAsStrings = [NSMutableArray array];
[datesAsDates enumerateObjectsUsingBlock:^(NSDate *date, NSUInteger idx, BOOL *stop){
     NSString *dateString = [dateFormater stringFromDate:date];
     [datesAsStrings addObject:dateString] 
}];

如果您想坚持使用 C 样式,请执行

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM"];
for (int i=0; i< [datesAsDates count]; i++) {       
    NSString *dateAsStr = [dateFormat stringFromDate:[dateAsDate objectAtIndex:i]]; 
    [arrayOfDatesAsStrings addObject:dateAsStr];
}

但由于有突变保护,枚举是首选。

于 2012-11-02T19:49:28.017 回答