Best way to generate NSData object with random bytes of a specific length?

后端 未结 9 1316
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 11:37

If I create a new NSData object of a specific size using dataWithBytes:length:, what is the most efficient way to create the input bytes (20 Mb worth) of random characters, pref

9条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 11:58

    Use arc4random_buf to fill the buffer with random bytes

    Obj-C

    + (nullable NSData *)radomDataOfSize:(size_t)sizeInBytes
    {
        void *buff = malloc(sizeInBytes);
        if (buff == NULL) {
            return nil;
        }
        arc4random_buf(buff, sizeInBytes);
    
        return [NSData dataWithBytesNoCopy:buff length:sizeInBytes freeWhenDone:YES];
    }
    

提交回复
热议问题