Ho una tabella Utenti e ho un mucchio di colonne nel modello di dati di base. Una delle colonne è user_id e sto cercando di ottenere il massimo user_id e aggiungere + 1 ad esso e passarlo all'oggetto successivo che verrà inserito. Ho seguito apple developer guide e implementato come suggerito. Ecco il codice che sto cercando di eseguire.Ottenere l'ID massimo dai dati di base e sqlite
Problema: il mio valore account_id che viene restituito è impostato su un numero strano che non esiste nemmeno nel database.
"account_id" = 139784529; Si suppone che sia 1 poiché ho salvato solo i dati principali.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Users" inManagedObjectContext:self._managedObjectContext];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"account_id"];
// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:@"max:"
arguments:@[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:@"maxAccountId"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType]; // For example, NSDateAttributeType
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:@[expressionDescription]];
// Execute the fetch.
NSError *error;
NSArray *objects = [self._managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
nextAccountId = [[[objects objectAtIndex:0] valueForKey:@"maxAccountId"] integerValue];
}
}
}
@catch (NSException *exception) {
NSLog(@"%@",[exception reason]);
}
return nextAccountId + 1;
Spero che qualcuno abbia affrontato il problema prima e l'abbia risolto.
Grazie
Il valore visualizzato assomiglia a un valore di garbage "normale" ottenuto dall'accesso a variabili non inizializzate. Impostare 'nextAccountId' su zero dovrebbe risolvere il problema. Non sono sicuro del perché '[oggetti contano]' restituisce zero, comunque. – dasblinkenlight
[numero oggetti] non restituisce zero. Non sono sicuro di cosa ti stai riferendo? – Harish
Non sembra che ci sia un'assegnazione di 'nextAccountId' in alcuni percorsi, in particolare quando il conteggio è zero. La risposta di Daniel in basso ha aggiunto un "altro" per coprirlo. – dasblinkenlight