How to convert NSData to Array of UInt8 ins iOS Ob

2019-08-19 10:31发布

问题:

I have Swift code for convert this method:

func DATA_TO_UINT8(_ d:Data) -> Array<UInt8> {
        return d.withUnsafeBytes {
            [UInt8](UnsafeBufferPointer(start: $0, count: (d.count)))
        }
}  

and now i want it in Objective C.

回答1:

To produce a stack based array try something like (code typed directly into answer, expect errors):

NSData *data = ...

UInt8 buf[data.length]; // local stack array
[data getBytes:buf length:data.length];

If you want a heap array you will need to use malloc to allocate the memory, if you don't actually need the array just a C pointer you can use the NSData bytes method.