これは、これを実装する方法とは正確に一致しない場合がありますが、うまくいけば、開始することができます。
ヘッダーまたは実装ファイルの上部のどこかにあります。
#import <stdlib.h>
#import <time.h>
実装の他の場所:
//
// 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
置換せずにサンプリングする必要がある場合は、重複を排除するために、ランダムなをサンプリングするだけでなく、オブジェクトNSSet
のを作成することができます。randomEntityIndex
NSNumber
int
この場合、注文したオブジェクトからサンプリングし、バッグからオブジェクトを引き出すときにオブジェクトをNSSet
削除し、セットからランダムなオブジェクトを選択するためにデクリメントします。NSNumber
myEntityCount
NSNumber