zoukankan      html  css  js  c++  java
  • IOS ID生成器

    //
    //  IdGenerator.m
    //  Copyright (c) 2014年 青岛拓宇网络科技有限公司. All rights reserved.
    //
    
    #import "IdGenerator.h"
    
    static long long time_stamp = 0;
    static long long time_stamp_now = 0;
    static NSMutableArray *temp = NULL;
    static NSNumber *random_n = NULL;
    static NSLock *theLock = NULL;
    
    @implementation IdGenerator
    
    /*
     *  获取下一个Id
     */
    + (long 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){
                //清空缓存,更新时间戳
                [temp removeAllObjects];
                time_stamp = time_stamp_now;
            }
            
            //判断缓存中是否存在当前随机数
            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
    

    不重复的Id生成器,理论上每秒钟最多可以生成8999条Id,实际上每秒钟约能生成6000条Id。

    转载请标明出处:http://www.cnblogs.com/anxin1225/p/3660506.html

    友情链接地址:http://c.jinhusns.com/

  • 相关阅读:
    docker
    opencart
    Why is setTimeout(fn, 0) sometimes useful?
    linux下php环境配置
    xampp for linux
    Where to go from here
    freefcw/hustoj Install Guide
    khan academy js
    SDWebImage
    基于OpenCV 的iOS开发
  • 原文地址:https://www.cnblogs.com/anxin1225/p/3660506.html
Copyright © 2011-2022 走看看