简体   繁体   中英

iOS: Generate random object ID

I want to use this method to fetch a random entity of core data:

randomQuote = [managedObjectContext objectWithID:randomID];

But I don't know how to set a random ID, which is an instance of NSManagedObjectID. Could anyone help me?

有一种生成uuid的方法:

  NSString *uuid = [[NSUUID UUID] UUIDString]; 

Use this:

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM