如何在目标c中将__NSCFString转换为NSData

问题描述 投票:0回答:1

将__NSCFString转换为NSData

当我尝试从我的NSDictonary获取数据时,应用程序崩溃

NSData *routeData = [dictSelectedScheduleTrip valueForKey:@"routeSerialize"];

崩溃日志[__NSCFString bytes]: unrecognized selector sent to instance 0x107310000

控制台代码

po [[dictSelectedScheduleTrip valueForKey:@"routeSerialize"] class]

__NSCFString

下面是我的NSData (Not added whole data because data is too long if you want to check all data please open below link)NSData

routeSerialize = "<d5112fa3 0c000000 382e3330 2e313031 2e313536 02000000 30000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00030200 00000710 008e015d 474cc1fe 5e7fa094 477dd52f 5f0b0400 9f000000 0c240003 01000402 04000200 00000104 00000000 00030100 04020400 02000000 01040000 0000000e 00000600 00000000>";

ios objective-c nsdata
1个回答
0
投票

我找到了解决方案。

原始答案@zaph

+ (NSData *)dataFromHexString:(NSString *)string
{
    string = [string lowercaseString];
    NSMutableData *data= [NSMutableData new];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    int length = string.length;
    while (i < length-1) {
        char c = [string characterAtIndex:i++];
        if (c < '0' || (c > '9' && c < 'a') || c > 'f')
            continue;
        byte_chars[0] = c;
        byte_chars[1] = [string characterAtIndex:i++];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    return data;
}
© www.soinside.com 2019 - 2024. All rights reserved.