1

I've the code in Java where p1 is an object of Pixel class which accesses an array pixels and assigns it the value (at right side) at the proper index. R G and B are some int values.

p1.pixels[index] = 0xff000000 | (R << 16) | (G << 8 ) | B;

I'm converting this code in Objective C as follows.But I don't know whether I have to mention the object name (insert object at p1.pixels) or inserting object at pixels does the same?

int newNumber = 0xff000000 | (R << 16) | (G << 8 ) | B;

NSNumber *yourNumber = [NSNumber numberWithInt:newNumber];
[pixels insertObject:yourNumber atIndex:index];
Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
user3863537
  • 101
  • 1
  • 12
  • Hard to say without more context. – nobody Aug 19 '14 at 18:12
  • The bit mashing appears to be equivalent, though it would give one a warmer feeling to use a length-specific int type. With the array you need to observe the caveat that Jeff states. – Hot Licks Aug 19 '14 at 18:22
  • You can use `NSNumber` literal syntax. Replace `[NSNumber numberWithInt:newNumber]` with `@(newNumber)`. – Zev Eisenberg Aug 19 '14 at 18:49

2 Answers2

2

NSArrays don't have a hard size limit like Java arrays do. They fill from the front, don't have default values (null in Java), and don't allow you to insert to an arbitrary location. The only way that the

[pixels insertObject:yourNumber atIndex:index];

line is safe is if there are greater than or equal to yourNumber elements already in the array.

If you really need that object to exist at a certain index, you should either fill the earlier positions with the other pixel values or a placeholder object like [NSNull null]

Also, int has different sizes on different Macs and iOS devices. If you want a specific sized integer, you should use one of the types like uint32, which is guaranteed to be 32-bits on every machine.

Jeff Holliday
  • 760
  • 6
  • 7
0

I think if you're manipulating pixels like this you're better off (in terms of performance and memory) to stick to plain-old-C.

If you wanted to create an UIImage object from the pixel data then you would use a buffer allocated using malloc(); for example (code taken from here - see the question for the rest of the code):

char* rgba = (char*)malloc(width*height*4);
for(int i=0; i < width*height; ++i) {
    rgba[4*i] = buffer[3*i];
    rgba[4*i+1] = buffer[3*i+1];
    rgba[4*i+2] = buffer[3*i+2];
    rgba[4*i+3] = 255;
}

Note that this is a byte buffer, not a uint32_t buffer, so adjust accordingly.

Using an NSArray populated with NSNumber objects will be much slower and take up much more space.

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242