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

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

    You might consider using CCRandomGenerateBytes function from CommonCrypto to generate random data. Like:

    func generateBytes(length : Int) throws -> NSData? {
        var bytes = [UInt8](count: length, repeatedValue: UInt8(0))
        let statusCode = CCRandomGenerateBytes(&bytes, bytes.count)
        if statusCode != CCRNGStatus(kCCSuccess) {
            return nil
        }
        return NSData(bytes: bytes, length: bytes.count)
    }
    

提交回复
热议问题