views:

644

answers:

1

I want to send out an NSArray, so I have to write it to an NSOutputStream first. The method should be :

- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)length

I can convert the array's pointer to uint8 _ t using :

(uint8_t *)arr

But how to get the length of bytes of the array? Do I have to save the array to a file and read it out as NSData?

+2  A: 

I can convert the array's pointer to uint8 _ t using :

(uint8_t *)arr

That's just a cast; it doesn't actually convert the array to a sequence of bytes. Even if you sent the private storage of the array over the wire, the contents of the array are just memory addresses to other objects. The memory addresses in your process are almost certainly not the same in the receiving process—and that's assuming that the receiving process is running Cocoa and would be expecting an NSArray!

You need to serialize the array's contents to some external representation that the receiver will be able to handle. You can do that by converting to a plist, creating an NSXMLDocument and getting its data, or assembling a custom-format representation by hand—but not with a cast alone.

But how to get the length of bytes of the array?

The array isn't a series of bytes; it's an object. As such, it doesn't have length, only (as an array) the count of objects in it. You need a series of bytes before you can get the series's length.

Do I have to save the array to a file and read it out as NSData?

You need to get an external representation of the array, preferably in an NSData object. Telling it to write (a plist of) itself to a file and reading the file back in is one way, but there are much better ways, which I listed above.

Peter Hosey