2015-11-02 79 views
0

我使用核心數據來保存我的數據,並且有一個名爲「timestamp」的屬性定義爲「NSDate」。我用我的助手類由下面的代碼獲取從核心數據的數據對象:類型從強ID轉換爲NSDate

- (id)getMaxValue:(NSString *)entityName forProperty:(NSString *)propertyName { 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName]; 

    fetchRequest.fetchLimit = 1; 
    fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:propertyName ascending:NO]]; 

    NSError *error = nil; 

    id maxValue = [self.context executeFetchRequest:fetchRequest error:&error].firstObject; 

    if ([maxValue count]) { 
     [self.context rollback]; 

     return [maxValue valueForKey:propertyName]; 
    } 
    else { 
     return nil; 
    } 

} 

在我控制我用下面的代碼來檢查是否有任何返回的結果,我得到它的時間戳:

id maxGroupsDate = [self.generalModel getMaxValue:@"MyEntityName" forProperty:@"timestamp"]; 
if (maxGroupsDate != nil) { 
    maxGroupsDate = (NSDate*) maxGroupsDate; 
    NSTimeInterval maxGroupsTimestamp = maxGroupsDate.timeIntervalSince1970; 
} 

但是它會導致這樣的錯誤:

Property 'timeIntervalSince1970' not found on object of type '__strong id' 

如何解決這個問題呢?

回答

0

這種說法沒有任何影響:

maxGroupsDate = (NSDate*) maxGroupsDate; 

相反,引進指定類型的新變量,也鑄造前檢查值NSDate

if ([maxGroupsDate isKindOfClass:[NSDate class]]) { 
    NSDate *date = (NSDate *)maxGroupsDate; 
    NSTimeInterval maxGroupsTimestamp = date.timeIntervalSince1970; 
} 

這最後一條語句不會也有很多效果,但我猜你只是爲了說明而添加的。