length
返回字符串的长度,如“Unicode 字符数”,它不返回其后备存储中的字节数。
要将 NSString 转换为 NSData ,您必须使用以下内容:
NSString *someString = @"123";
NSData *someData = [someString dataUsingEncoding:NSUTF8StringEncoding];
你所做的,适用于仅包含 ASCII 的 UTF8,因为即使在 UTF8 中,ASCII 字符也只占用 1 个字节。巧合的是,字符串的“逻辑”长度与其后备存储的大小相匹配。
尝试使用包含 ASCII 范围之外的字符的字符串,您将看到不同的结果:
NSString *asciiString = @"123";
NSLog(@"\"%@\" - Length: %ld", asciiString, (long)[asciiString length]);
NSData *asciiData = [asciiString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Data length: %ld", [asciiData length]);
NSString *utf8String = @"";
NSLog(@"\"%@\" - Length: %ld", utf8String, (long)[utf8String length]);
NSData *utf8Data = [utf8String dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Data length: %ld", [utf8Data length]);
utf8String = @"oö";
NSLog(@"\"%@\" - Length: %ld", utf8String, (long)[utf8String length]);
utf8Data = [utf8String dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Data length: %ld", [utf8Data length]);
产量:
"123" - Length: 3
Data length: 3
"" - Length: 2
Data length: 4
"oö" - Length: 2
Data length: 3