Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,
I know this is suppose to be very straight forward and simple but i have been trying to convert NSData to NSString using Obj-C but the outputs are not what I really wanted.

my NSData variable:
Objective-C
NSData *blockData = [NSData dataWithBytes:&data length:sizeof(data)];

I'm trying to print it in NSLog like below:
NSLog(@"sneding block: %@", blockData);

the output is like:
018-06-13 08:05:18.641965-0400 sendData[3016:1171273] sneding: <0000e992 ffff0300 00884242 4242ffff ffff>

I need the output to be in string or numbers not hex, i have done it in java by converting byte[] array to string: Arrays.toString(byte[]) the output something like: [-24,14,60,103,-119,14,-118,12,-117,13,18,84,81,-118,10,-117,11,-22]

any ideas?
Thanks in advance

What I have tried:

I tried to use NSUTF8StringEncoding
Objective-C
NSString *str = [[NSString alloc] initWithData:blockData encoding:NSUTF8StringEncoding];//returns null

also tried NSASCIIStringEncoding with no luck
Objective-C
[[NSString alloc] initWithData:blockData encoding:NSASCIIStringEncoding];//returns ascii codes
Posted
Updated 13-Jun-18 5:37am

1 solution

You can do it like this:

NSMutableString * str = [NSMutableString string];
for (int i = 0; i<sizeof(data); i++)
{
    [str appendFormat:@"%d ", data[i]];
}

NSLog(@"%@",str);
 
Share this answer
 
Comments
Samira Radwan 13-Jun-18 13:36pm    
Thank you!
this solution works very well when using array of bytes or signed char. but if `data` is of type `NSData` I got error: expected method to read array element not found on object of type NSData. we can't just read data[i] if it's NSData
[no name] 13-Jun-18 13:48pm    
If you have an object blockData of type NSData, you can convert it into a byte array data like so:
data = [blockData bytes];

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900