我需要生成一些整数值,这些值在理论上不会重复。我知道有 arc4random() 函数,但我不确定如何将其与当前日期或其他内容一起使用 :(
我需要生成一些整数值,这些值在理论上不会重复。我知道有 arc4random() 函数,但我不确定如何将其与当前日期或其他内容一起使用 :(
这将返回一个非常类似于在MySQL中生成的UUID的唯一键。
+ (NSString *)uuid
{
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return [(NSString *)uuidStringRef autorelease];
}
ARC版本:
+ (NSString *)uuid
{
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return (__bridge_transfer NSString *)uuidStringRef;
}
__bridge_transfer
иҖҢдёҚжҳҜ__bridge
еҗ—пјҹ - derpoliuk一种简单的生成UUID(适用于iOS 6或更高版本)的方法。
Objective-C:
NSString *UUID = [[NSUUID UUID] UUIDString];
Swift 3+:
let uuid = UUID().uuidString
每次调用此函数,它将生成类似于 68753A44-4D6F-1226-9C60-0050E4C00067 的唯一标识符,即使跨多个设备和位置也是如此。
NSManagedObject
的objectID
应该可以满足您的需求,无需额外的努力。@interface UIApplication (utilities)
- (NSString*)getUUID;
@end
@implementation UIApplication (utilities)
- (NSString*)getUUID {
NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
static NSString *uuid = nil;
// try to get the NSUserDefault identifier if exist
if (uuid == nil) {
uuid = [standardUserDefault objectForKey:@"UniversalUniqueIdentifier"];
}
// if there is not NSUserDefault identifier generate one and store it
if (uuid == nil) {
uuid = UUID ();
[standardUserDefault setObject:uuid forKey:@"UniversalUniqueIdentifier"];
[standardUserDefault synchronize];
}
return uuid;
}
@end
UUID()是一个函数,用于生成唯一的标识符。
NSString* UUID () {
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return (__bridge NSString *)uuidStringRef;
}
NSString *uuid = [[UIApplication sharedApplication] getUUID];
self.uid = [NSNumber numberWithInteger:[NSDate timeIntervalSinceReferenceDate] * 10000];
你没有说必须是随机的。那么为什么不从某个数字开始,然后只需将上次生成的数字加1。
这种方法应该至少给你提供40亿个独特的数字:
-(NSInteger)nextIdentifies;
{
static NSString* lastID = @"lastID";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSInteger identifier = [defaults integerForKey:lastID] + 1;
[defaults setInteger:identifier forKey:lastID];
[defaults synchronize];
return identifier;
}
NSInteger maxKey = -1;
for(NSString *key in [YOUR_DICTIONARY allKeys])
{
NSInteger intKey = [key integerValue];
if(intKey > maxKey)
{
maxKey = intKey;
}
}
NSString *newKey = [NSString stringWithFormat:@"%d", maxKey + 1];
如果您使用增量为1的例程,那么一定要小心,特别是如果您的应用程序被删除并重新加载到iDevice上,那么您将不再拥有保存的默认数字。它将从头开始。如果您正在存储用户的分数,您可能还想保存他们的最高分数。最好检查某个日期后的秒数(或毫秒)的时间例程。如上所述的GUID也很好,如果您需要这种唯一性。
return counter++
的问题在哪里?这会在重复之前生成完整的 int 范围。 - Dunes