user387184
user387184

Reputation: 11053

Converting Java byte array into iOS NSData

In Java I have a byte array representation which in iOS I have represented as NSData.

Everything works fine - it's just that some access methods seem rather clumsy in iOS compared to Java.

Accessing a single byte in Java: byteArray[i]

while in iOS I keep using this where byteArray is a NSData:

 Byte b;
 [byteArray getBytes: &b range: NSMakeRange( i, 1 )];

Isn't there a more direct way of writing this similar to Java?

Upvotes: 0

Views: 1454

Answers (1)

Arndt Bieberstein
Arndt Bieberstein

Reputation: 1128

Well considering not using a NSData Object you could transform it to a const void* like this.

NSdata *data = your data stuff
NSUInteger i = 1;
const char * array = [data bytes];
char c = array[i];

Note This kind of array is read only! (const void *)

Otherwise you'll have to use the functions you already mentioned or some others Apple provides.

Edit

Or you could add some category to NSData

@interface NSData(NSDataAdditions)

- (char)byteAtIndex:(NSUInteger)index;

@end

@implementation NSData(NSDataAdditions)

- (char)byteAtIndex:(NSUInteger)index {
    char c;
    [self getBytes: &c range: NSMakeRange( index, 1 )];
    return c;
}

@end

And then access your Array like this:

NSdata *data = your data stuff
char c = [data byteAtIndex:i];

Upvotes: 3

Related Questions