0

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?

1 Answer 1

3

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.