How to convert Objective-C NSData to Swift Data?

566 views Asked by At

I have a NSData in Objective-C, the NSData has value 0x10, code like bellows:

@implementation BufUtil
+ (NSData *_Nonnull) getOCBuf {
    std::vector<uint8_t> sendData = {0x10};
    NSData * reqBuf = [[NSData alloc] initWithBytesNoCopy:sendData.data() length:sendData.size() freeWhenDone:false];
    NSLog(@"getOCBuf, oc NSData reqBuf:%@", reqBuf);
    return reqBuf;
}
@end

Then I use the data in Swift, Swift auto convert Objective-C NSData to Swift Data, but strange things happen, the value in Swift Data is 0x60, code like belows:

public func getOCBuf() -> Data {
    let data = BufUtil.getOCBuf();
    print("getOCBuf: swift data: \(data.hexEncodedString())")
    return data
}

the log is like:

getOCBuf, oc NSData reqBuf:{length = 1, bytes = 0x10}
getOCBuf: swift data: 60

Now I am confused with what happened. Why 0x10 turn into 0x60, the two number not Binary complement.

Can anybody help me, thanks.

the code:
https://github.com/oncealong/SwiftOcDataConvert

1

There are 1 answers

0
bluesky On

It's my falut.

I copy code "how to convert from std::vector to NSData" from stackoverflow, but the code use [NSData alloc] initWithBytesNoCopy, which lead to all this.

the momory associate with the std::vector has freed after the getOCBuf func return. but the oc NSData and swift Data don't know. it use the origin address and found different value.

To be honest, the app should be crashed, and give a reason.