Page 1 of 1

C-Style Arrays of Objective-C objects

Posted: Sun Sep 05, 2004 9:55 pm
by scottstevenson
A simple one, but I think sometimes people forget that you're free to use c-style arrays of Objective-C objects where you need ever last ounce of speed:

Code: Select all

// choose arbitrary size for array

int count = 20;

// allocate memory for array of pointers

NSString ** stringArray = (NSString **)malloc ( sizeof ( NSString *) * count );

// create objects and log them to the console

for (i = 0; i < count; i++)
{
    stringArray[i] = [[NSString alloc] initWithFormat:@"String %d",(i+1)];
    NSLog(@"stringArray[%d]: %@", i, stringArray[i]);
}

// release objects

NSString * theString;
for (i = 0; i < count; i++)
{
    theString = stringArray[i];
    [theString release];
}   

// free malloc'd memory

free (stringArray);




Also worth looking at NSArray's -getObjects:

- Scott