我想使用此方法来获取核心数据的随机实体:
randomQuote = [managedObjectContext objectWithID:randomID];
但我不知道如何设置随机ID,这是NSManagedObjectID的一个实例。有谁可以帮助我?
答案 0 :(得分:1)
有一种生成uuid的方法:
NSString *uuid = [[NSUUID UUID] UUIDString];
答案 1 :(得分:0)
使用此:
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext: managedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [managedObjectContext countForFetchRequest:myRequest error:&error];
NSUInteger offset = myEntityCount - (arc4random() % myEntityCount);
[myRequest setFetchOffset:offset];
[myRequest setFetchLimit:1];
NSArray* objects = [managedObjectContext executeFetchRequest error:&error];
id randomQuote = [objects objectAtIndex:0];