IOS ID產生器

來源:互聯網
上載者:User

////  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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.