关于C#:如何将nsstring值转换为nsdata?

How do I convert an NSString value to NSData?

如何将NSString值转换为NSData


1
2
NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];


1
2
3
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

你可以从这个链接带参考


的:

1
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

然后NSJSONSerialization:JSONObjectWithDataí与自由的感觉。

修正在回答关于null

6.注释和文档,官方的回答是,verifications,更新关于这一alleged null:去除

  • 通过详实的datausingencoding:

    Return Value

    The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument

  • 通过详实的getcstring MaxLength编码:::::与cstringusingencoding

    note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator


  • 敏捷开发在未来的情况。

    在转换从/到nsdata NSString的字符串

    1
    var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

    Objective-C。

    1
    2
    3
    NSString *str = @"test string";
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
    NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    斯威夫特:

    1
    2
    3
    let str ="test string"
    let data = NSKeyedArchiver.archivedData(withRootObject: str)
    let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String


    第一关,你应该使用dataUsingEncoding:UTF8String而去。你只需要使用UTF8String当你在这C字符串编码。

    然后,UTF-16通,而只是在你的NSUnicodeStringEncodingNSUTF8StringEncodingdataUsingEncoding:消息。


    如果你将是迅速的,是从StringData转换到。

    1
    2
    3
    let myString ="test"
    let myData = myString.data(using: .utf8)
    print(myData) // Optional(Data)

    1
    2
    NSString *str = @"hello";
    NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];


    Objective-C。

    nsdata NSString):

    1
    2
    NSString* str= @"string";
    NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

    nsdata NSString):

    1
    NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

    斯威夫特:

    字符串到日期:

    1
    2
    var testString ="string"
    var somedata = testString.data(using: String.Encoding.utf8)

    数据字符串:

    1
    var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!

    1
    2
    NSString *str = @"Banana";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

    Objective - C的

    1
    2
    NSString *str = @"Hello World";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

    斯威夫特

    1
    2
    let str ="Hello World"
    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)