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.

C. A. McCann
  • 76,893
  • 19
  • 209
  • 302
Raju
  • 3,459
  • 12
  • 37
  • 30

2 Answers2

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 };
mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • what's the difference if an unsigned char was used? – whyoz Mar 03 '18 at 15:34
  • 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)];` ? – rustyMagnet Apr 30 '20 at 14:42
  • 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! – Max Hiroyuki Ueda Jan 25 '23 at 21:30
7

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

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
  • 1
    These links should be updated - NSData: https://developer.apple.com/documentation/foundation/nsdata - NSMutableData: https://developer.apple.com/documentation/foundation/nsmutabledata – whyoz Mar 02 '18 at 03:52