Questo potrebbe non essere esattamente come si implementa questa, ma si spera che permette di iniziare.
qualche parte nel vostro nell'intestazione o nella parte superiore del file di implementazione:
#import <stdlib.h>
#import <time.h>
Altrove nell'implementazione:
//
// get count of entities
//
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext:myManagedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [myManagedObjectContext countForFetchRequest:myRequest error:&error];
[myRequest release];
//
// add another fetch request that fetches all entities for myEntityName -- you fill in the details
// if you don't trigger faults or access properties this should not be too expensive
//
NSArray *myEntities = [...];
//
// sample with replacement, i.e. you may get duplicates
//
srandom(time(NULL)); // seed random number generator, so that you get a reasonably different series of random integers on each execution
NSUInteger numberOfRandomSamples = ...;
NSMutableSet *sampledEntities = [NSMutableSet setWithCapacity:numberOfRandomSamples];
for (NSInteger sampleIndex = 0; sampleIndex < numberOfRandomSamples; sampleIndex++) {
int randomEntityIndex = random() % myEntityCount; // generates random integer between 0 and myEntityCount-1
[sampledEntities addObject:[myEntities objectAtIndex:randomEntityIndex]];
}
// do stuff with sampledEntities set
Se è necessario campionare senza sostituzione, di eliminare i duplicati, si potrebbe creare un oggetto randomEntityIndex
NSNumber
di oggetti NSSet
, anziché campionare casualmente int
s.
In questo caso, il campione da una ordinata NSSet
, rimuovere NSNumber
oggetti durante si tira fuori dalla borsa, e decrementa myEntityCount
ai fini di scegliere un NSNumber
oggetto casuale dal set.
fonte
2010-05-13 22:17:08
Ulteriori informazioni: le cose che sto cercando di ottenere sono oggetti con due proprietà, una stringa qualsiasi da 1 a 50 caratteri e una chiave primaria pseudo che ho pensato potrebbe aiutare con il bit di selezione casuale. Riesco a ristrutturare il modello anche se, se necessario, ancora prototipando questo ventosa. – nickthedude
Questo commento dovrebbe essere aggiunto alla tua domanda. –