Friday, May 31, 2013

NSArray getObjects example in Objective C (iOS).

NSArray getObjects

Copies the objects contained in the array that fall within the specified range to aBuffer.

- (void)getObjects:(id[])aBuffer range:(NSRange)aRange

Parameters of [NSArray getObjects]
A C array of objects of size at least the length of the range specified by aRange.
A range within the bounds of the array.
If the location plus the length of the range is greater than the count of the array, this method raises an NSRangeException.

Discussion of [NSArray getObjects]
The method copies into aBuffer the objects in the array in the range specified by aRange; the size of the buffer must therefore be at least the length of the range multiplied by the size of an object reference, as shown in the following example (this is solely for illustration—you should typically not create a buffer simply to iterate over the contents of an array):

NSArray *mArray = // an array with at least six elements...;
id *objects;

NSRange range = NSMakeRange(2, 4);
objects = malloc(sizeof(id) * range.length);

[mArray getObjects:objects range:range];

for (i = 0; i < range.length; i++) {
NSLog(@"objects: %@", objects[i]);
NSArray getObjects example.
An alternative to mouviciel's answer is to use NSArray's getObjects:range: method.

id cArray[10];
NSArray *nsArray = [NSArray arrayWithObjects:@"1", @"2" ... @"10", nil];

[nsArray getObjects:cArray range:NSMakeRange(0, 10)];
Or, if you don't know how many objects are in the array at compile-time:

NSUInteger itemCount = [nsArray count];
id *cArray = malloc(itemCount * sizeof(id));

[nsArray getObjects:cArray range:NSMakeRange(0, itemCount)];

... do work with cArray ...


Example of [NSArray getObjects].
NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);

[someArray getObjects:cArray range:copyRange];

/* use cArray somewhere */


NSArray getObjects example.
- (id) initWithArray: (NSArray*)array
  unsigned    c = [array count];
  id        objects[c];

  [array getObjects: objects];
  self = [self initWithObjects: objects count: c];
  return self;

End of NSArray getObjects example article.