Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read bytes from NSData

Can anyone suggest a method to read bytes from NSData (like read function in @interface NSInputStream : NSStream)

like image 731
Deepak Pillai Avatar asked Sep 17 '12 04:09

Deepak Pillai


People also ask

What is NS data?

NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.

What is Nsmutabledata in Swift?

From Apple's documentation: NSData and its mutable subclass NSMutable​Data provide data objects, object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects.

What is byte array in Swift?

In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.


2 Answers

How to read binary bytes in NSData? may help you:

NSString *path = @"…put the path to your file here…";
NSData * fileData = [NSData dataWithContentsOfFile: path];
const char* fileBytes = (const char*)[fileData bytes];
NSUInteger length = [fileData length];
NSUInteger index;

for (index = 0; index<length; index++) {
   char aByte = fileBytes[index];
   //Do something with each byte
}
like image 91
Pravitha V Avatar answered Oct 07 '22 10:10

Pravitha V


You can also create an NSInputStream from an NSData object, if you need the read interface:

NSData *data = ...;
NSInputStream *readData = [[NSInputStream alloc] initWithData:data];
[readData open];

However, you should be aware that initWithData copies the contents of data.

like image 21
Martin R Avatar answered Oct 07 '22 11:10

Martin R