如何将NSString值转换为NSData?
当前回答
对于Swift 3,你将主要从字符串转换为数据。
let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
其他回答
objective - c:
NSString *str = @"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
迅速:
let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
迅速:
快5.倍
let myStringToConvert = "My String to Convert in Data"
let myData = myStringToConvert.data(using: .utf8)
字符串到数据:
var myStringToConvert = "My String to Convert in Data"
var myData = myStringToConvert.data(using: String.Encoding.utf8)
数据到字符串:
var backToMyString = String(data: myData!, encoding: String.Encoding.utf8) as String!
OBJECTIVE - C:
德国…
NSString* myStringToConvert= @"My String to Convert in Data";
NSData* myData=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
ns戴:
NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
objective - c:
NSString to NSData:
NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
迅速:
字符串到数据:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
数据到字符串:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
推荐文章
- 我如何获得iOS 7默认的蓝色编程?
- UITapGestureRecognizer破坏UITableView didSelectRowAtIndexPath
- 在Objective-C中@property保留,赋值,复制,非原子
- 6.5英寸屏幕的App store截图大小是多少?
- 我如何在NSAttributedString中创建一个可点击的链接?
- iOS测试/规格TDD/BDD以及集成和验收测试
- 停止UIWebView垂直“弹跳”?
- 启动屏幕故事板不显示图像
- 对未渲染的视图进行快照,结果是一个空快照
- 是否可以为iPhone应用程序(如YouTube和地图)注册一个基于http+域的URL方案?
- 模拟器错误fbssystemservicdomain代码4
- 开始使用instancetype而不是id是否有益?
- 改变UISegmentedControl的字体大小
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?
- 为什么Objective-C文件使用。m扩展名?