16

How can I create a byte array in Objective-C?

I have some data like this:0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, that I want to prepare as a byte array.

2 Answers 2

36

You can simply use plain C syntax, which is available in Objective-C:

const char myByteArray[] = {
    0x12,0x23,0x34,0x45,
    0x56,0x67,0x78,0x89,
    0x12,0x23,0x34,0x45,
    0x56,0x67,0x78,0x89 };
Sign up to request clarification or add additional context in comments.

3 Comments

what's the difference if an unsigned char was used?
I love the C byte array but what happens if you want multiple byte arrays inside NSArray? Implicit conversion of a non-Objective-C pointer type 'const char *' to 'id _Nonnull' is disallowed with ARC. I like the answerr below from @Georg. NSData *data = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)]; ?
In case I have some data like this (a NSString object) @"0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89", how would I programmatically create an unsigned char array? Thanks in advance!
7

Either use the plain C solution given by mouviciel or read the class description of NSData and NSMutableData.

1 Comment

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.