iOS:生成随机对象ID

时间:2014-09-21 05:20:59

标签: ios objective-c iphone

我想使用此方法来获取核心数据的随机实体:

randomQuote = [managedObjectContext objectWithID:randomID];

但我不知道如何设置随机ID,这是NSManagedObjectID的一个实例。有谁可以帮助我?

2 个答案:

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