//// IdGenerator. m // Copyright (c) 2014 Qingdao toyu Network Technology Co., Ltd. all rights reserved. // # import "IdGenerator. h "static long time_stamp = 0; static long time_stamp_now = 0; static NSMutableArray * temp = NULL; static NSNumber * random_n = NULL; static NSLock * theLock = NULL; @ implementation IdGenerator/** get the next Id */+ (long) next {if (theLock = NULL) theLock = [[NSLock alloc] init]; if (temp = NULL) temp = [[NSMutableArray alloc] init]; @ synchronized (theLock) {time_stamp_now = [[NSDate date] timeIntervalSince1970]; if (time_stamp_now! = Time_stamp) {// clear the cache and update the timestamp [temp removeAllObjects]; time_stamp = time_stamp_now ;} // determine whether the cache contains the current random number while ([temp containsObject :( random_n = [NSNumber numberWithLong: arc4random () % 8999 + 1000]); if ([temp containsObject: random_n]) {return-1;} [temp addObject: [NSNumber numberWithLong: [random_n longValue];} return (time_stamp * 10000) + [random_n longValue];} @ end
In theory, up to 8999 IDS can be generated every second. In fact, about 6000 IDS can be generated every second.
Reprinted please indicate the source: http://www.cnblogs.com/anxin1225/p/3660506.html
Links: http://c.jinhusns.com/