objective-c: how to assign string to NSMutableData?

后端 未结 4 1952
挽巷
挽巷 2021-01-21 19:40

I am to send data to digital meter for which I want data in NSMutableData form. I am trying to assign it data but getting errors.

NSMutableData *body = [[NSMuta         


        
相关标签:
4条回答
  • 2021-01-21 20:01

    You could convert NSString into NSData with[@"1" dataUsingEncoding:NSUTF8StringEncoding], the rest of your code is OK.

    NSMutableData *body = [[NSMutableData alloc] initWithData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]];
    
    0 讨论(0)
  • 2021-01-21 20:06
    NSString *str = @"ABC";    
    NSMutableData* body = (NSMutableData *)[str dataUsingEncoding:NSUTF8StringEncoding];
    
    0 讨论(0)
  • 2021-01-21 20:07
    NSMutableData* body = [[@"1" dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    
    0 讨论(0)
  • 2021-01-21 20:08

    You can't convert directly from an NSString to NSMutableData, you have to encode the string as NSData first. (There are several ways to go from NSData to NSMutableData, but I think mutableCopy is the clearest.);

    Try this:

    NSString *yourString  = @"Your string text";
    NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *body = [data mutableCopy];
    
    0 讨论(0)
提交回复
热议问题