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

后端 未结 9 1498
佛祖请我去吃肉
佛祖请我去吃肉 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 12:13

    Here's a 3-liner swift version:

    Swift 2

    let length = 2048
    let bytes = [UInt32](count: length, repeatedValue: 0).map { _ in arc4random() }
    let data = NSData(bytes: bytes, length: bytes.count * sizeof(UInt32))
    

    Swift 3

    let bytes = [UInt32](repeating: 0, count: length).map { _ in arc4random() }
    let data = Data(bytes: bytes, count: length)
    

提交回复
热议问题