2010-05-10 16 views
7

Sto cercando di trovare la data più vecchia in un determinato attributo in Dati principali. Ho trovato an example in the Core Data Programming Guide che pretende di fare esattamente questo, ma continuo a ricevere un errore selezionato non riconosciuto quando lo eseguo.Dati principali: tentativo di trovare la data minima per un attributo in un'entità

Il mio codice (con modifiche solo minime dall'esempio di Apple):

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext: ctx]; 
[request setEntity:entity]; 

// Specify that the request should return dictionaries. 
[request setResultType:NSDictionaryResultType]; 

// Create an expression for the key path. 
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"startedAt"]; 

// Create an expression to represent the minimum value at the key path 'creationDate' 
NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" arguments:[NSArray arrayWithObject:keyPathExpression]]; 

// Create an expression description using the minExpression and returning a date. 
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; 

// The name is the key that will be used in the dictionary for the return value. 
[expressionDescription setName:@"minDate"]; 
[expressionDescription setExpression:minExpression]; 
[expressionDescription setExpressionResultType:NSDateAttributeType]; 

// Set the request's properties to fetch just the property represented by the expressions. 
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; 

// Execute the fetch. 
NSError *error; 
NSArray *objects = [ctx executeFetchRequest:request error:&error]; 

e l'errore:

-[NSCalendarDate count]: unrecognized selector sent to instance ... 

che è strano dato che 1) NSCalendarDate è deprecato e 2) I' sicuramente non sto chiamando il conto.

Qualsiasi aiuto sarebbe più apprezzato!

+0

È "startedAt" Definito come NSDate? ed è indicizzato. Ho usato quasi il codice esatto per te e funziona benissimo. Penso che sia meglio che usare un ordinamento –

risposta

12

Perché non aggiungere semplicemente un descrittore di ordinamento per ordinare in base a startedDate crescente e quindi avere solo l'oggetto restituire richiesta 1 di recupero?

+0

Beh, ovviamente perché non stavo pensando ... :-) Funziona. Grazie! – AndrewO

+0

Questo è ... molto intelligente. Applausi. – duci9y

+0

Penso che usare un'espressione su un tipo sarebbe più efficiente. –

0

Questo è il mio codice che funziona. Non riesco a vedere alcuna differenza significativa per il tuo codice e forse è nella definizione del modello di dati di base. Assicurati che la tua data sia NSDate e che sia indicizzata.

- (NSDate *)lastSync:(PHAssetMediaType)mediaType { 
    NSEntityDescription *entity = [NSEntityDescription entityForName:kMediaItemEntity inManagedObjectContext:self.managedObjectContext]; 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    fetchRequest.entity = entity; 
    fetchRequest.resultType = NSDictionaryResultType; 

    NSMutableArray *predicates = [NSMutableArray array]; 
    [predicates addObject:[NSPredicate predicateWithFormat:@"%K=%d", kMediaType,mediaType]]; 
    [predicates addObject:[NSPredicate predicateWithFormat:@"%K=%d", kMediaProviderType,self.mediaProviderType]]; 
    NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates: predicates]; 
    fetchRequest.predicate = predicate; 

    // Create an expression for the key path. 

    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:kSyncTime]; 
    // Create an expression to represent the function you want to apply 

    NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" 
                  arguments:@[keyPathExpression]]; 

    // Create an expression description using the maxExpression and returning a date. 
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; 
    [expressionDescription setName:@"maxDate"]; 
    [expressionDescription setExpression:maxExpression]; 
    [expressionDescription setExpressionResultType:NSDateAttributeType]; 

    // Set the request's properties to fetch just the property represented by the expressions. 
    fetchRequest.propertiesToFetch = @[expressionDescription] ; // @[kSyncTime]; 

    NSError *fetchError = nil; 
    id requestedValue = nil; 

    // fetch stored media 
    NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError]; 
    if (fetchError || results == nil || results.count == 0) { 
     return [NSDate dateWithTimeIntervalSince1970:0]; 
    } 
    requestedValue = [[results objectAtIndex:0] valueForKey:@"maxDate"]; 
    if (![requestedValue isKindOfClass:[NSDate class]]) { 
     return [NSDate dateWithTimeIntervalSince1970:0]; 
    } 
    DDLogDebug(@"sync date %@",requestedValue); 
    return (NSDate *)requestedValue; 
} 
Problemi correlati