Search code examples
iosobjective-cswiftbyteuint8t

How to convert NSData to Array of UInt8 ins iOS Objective C?


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.


Solution

  • 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.