objective-c: how to assign string to NSMutableData

2020-04-14 07:47发布

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 = [[NSMutableData alloc] initWithData:[NSData @"1"];

I want to asign string e.g. "1", "start" etc to NSMutableData.

4条回答
Explosion°爆炸
2楼-- · 2020-04-14 08:15

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];
查看更多
Rolldiameter
3楼-- · 2020-04-14 08:20
NSMutableData* body = [[@"1" dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
查看更多
家丑人穷心不美
4楼-- · 2020-04-14 08:27
NSString *str = @"ABC";    
NSMutableData* body = (NSMutableData *)[str dataUsingEncoding:NSUTF8StringEncoding];
查看更多
Juvenile、少年°
5楼-- · 2020-04-14 08:29

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]];
查看更多
登录 后发表回答