문제

다음 코드가 있습니다.

   -(NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section { 
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];


NSString *sectionName = [sectionInfo name];
NSLog(@"sectionName %@", sectionName);


NSString *convDate = [dateFormatter stringFromDate: (NSDate *)sectionName];
NSLog(@"convDate %@", convDate);
return [NSString stringWithFormat:@"%@", [sectionInfo name]];
 }

기본적으로 "2009-12-04 00:00:00 +1100"과 같은 문자열 날짜 인 TitleforheaderItsection을 더 짧은 문자열로 변환해야합니다. 그래서 DateFormatter setDatestyle과 같은 것을 사용하여 변환을 시도했지만 NSLOG를 콘솔로 출력하면 다음을 얻습니다.

2009-12-22 09 : 42 : 10.156 앱 [94614 : 207] 섹션 이름 2009-12-04 00:00:00 +1100 2009-12-22 09 : 42 : 10.157 앱 [94614 : 207] Convdate

분명히 Convdate는 아무것도 얻지 못하지만 [SectionInfo Name]은 문자열이어야합니다. 자체 NSString 변수로 구문 분석했는데 왜 DateFormatter를 구현할 수 없습니까?


조금 더 많은 정보 : 나는 코드 스 니펫이 다음과 같이 이전의 것들 중에서 날짜를 구문 분석합니다.

   if ([currentElement isEqualToString: @"date"]) { 
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateFormat:@"eee, dd MMM yyyy"];
    NSDate *convDate = [dateFormatter dateFromString:string];
    if (self.isComment){
        [currentComment setDate: convDate];         
    }else if (self.isPost)  
        NSLog(@"convDate is %@", convDate);
        [currentPost setDate: convDate];

이제 이것을 디버그 할 때, 본질적으로 원시 문자열은 "Sat, 27 Nov 2009 17:16:00 -800"이지만, convdate를 보면 "2009-11-27 00:00:00:00 +가됩니다. 1100 ". 이유는 확실하지 않지만 어쨌든 그것이 저장되는 것입니다. 나는 그것이 내가 언급 한 스타일과 일치 할 것이라고 생각했을 것입니다. 그래서 DateFormatter 형식을 다른 유형으로 변경하면, 그것은 위로가되고 convdate는 nil이 될 것입니다.

내 포스트 컨트롤러를 되돌아 보면 : 관심있는 스 니펫이 있습니다.

- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Post" inManagedObjectContext: ApplicationController.sharedInstance.managedObjectContext]];
    NSArray *sortDescriptors = nil;
    NSString *sectionNameKeyPath = @"date";



    NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(PostSite.name like '%@')", self.site.name]];

    [fetchRequest setPredicate:pred];

    sortDescriptors = [NSArray arrayWithObject:[[NSSortDescriptor alloc] 
                                                 initWithKey:@"date" ascending:NO] ];
    [fetchRequest setSortDescriptors:sortDescriptors];
    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext: 
                                ApplicationController.sharedInstance.managedObjectContext 
                                                                     sectionNameKeyPath:sectionNameKeyPath cacheName:@"PostCache"];
}    

return fetchedResultsController;

}

날짜별로 정렬하고 코드를 TitleforHeaderItsection으로 정렬하고 문자열 날짜를 형식화하여 더 많이 보일 수 있습니다.

감사합니다

도움이 되었습니까?

해결책

예상치 못한 행동을 취한 이유는 구문 분석 중에 날짜 형식을 설정했기 때문입니다.

[dateFormatter setDateFormat:@"eee, dd MMM yyyy"];

시간 정보가 없기 때문에 날짜에 시차가 발생했습니다.

또한 구문 분석하는 동안 설정하고있었습니다 convDate ~와 함께

NSDate *convDate = [dateFormatter dateFromString:string];

nsdate를 저장하고 있습니다 결정적으로 nsfetchResultsController가 호출 중입니다 description 선택기 ON convDate NSString이 아니기 때문입니다.

NSDateFormatter가 ISO 날짜 형식을 인식 할 수없는 이유를 완전히 확신하지 못합니다.

다른 팁

코드가 작동하지 않는 이유는 때문입니다

[sectionInfo name]

nsdate 객체가 아닌 nsstring 객체를 반환합니다.

[dateFormatter stringFromDate:];

NSDATE에 NSString을 캐스트 할 수는 없습니다.

대신에,

- (NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    NSString *sectionName = [sectionInfo name];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    NSString *convDate = [dateFormatter stringFromDate:[dateFormatter dateFromString:sectionName]];
    [dateFormatter release];

    return convDate;
}

또한 특정 이유가 없다면 물체를 자동 조정하지 마십시오.

나는 가서 해결책을 찾았다 http://iosdevelopertips.com/cocoa/date-formatters-examples-take-2.html 그리고 사용 http://unicode.org/reports/tr35/#date_format_patterns 가이드로서, 변수가 들어오는 문자열과 일치 할 때까지 코드를 디버깅했습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top