Pages

Wednesday, December 30, 2009

Objective-C. NSArray, NSMutableArray

It's a collection of objects.
#import <Foundation/NSObject.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSstring.h>
#import <Foundation/NSAutoreleasePool.h>


int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSArray *months = [NSArray arrayWithObjects:
@"January", @"February",
@"March", @"April", @"May",
@"June", @"July", @"August",
@"September", @"October", @"November",
@"December", nil];

NSLog(@"Month Name");
NSLog(@"-------------");

int i;
for (i = 0; i < [months count]; ++i)
{
NSLog(@"%2i. %@", i + 1, [months objectAtIndex: i]);
}

[pool drain];
return 0;
}



There is also a mutable version of the array: NSMutableArray. The following program generates the prime numbers and store them in the array (because the number of the elements in the array is unknown in the beginning, NSMutableArray is used):
#import <Foundation/NSObject.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSValue.h>

#define MAX_PRIME 50

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSMutableArray* primes = [NSMutableArray arrayWithCapacity: 20];

[primes addObject: [NSNumber numberWithInteger: 2]];
[primes addObject: [NSNumber numberWithInteger: 3]];

BOOL isPrime;
int p, i, prevPrime;
for (p = 5; p < MAX_PRIME; p += 2)
{
isPrime = YES;
i = 1;
do {
prevPrime = [[primes objectAtIndex: i] integerValue];
if ( p % prevPrime == 0)
isPrime = NO;

++i;
} while (isPrime == YES && p / prevPrime >= prevPrime);

if (isPrime)
[primes addObject: [NSNumber numberWithInteger: p]];
}

for (i = 0; i < [primes count]; ++i)
NSLog(@"%li", (long)[[primes objectAtIndex: i] integerValue]);


[pool drain];
return 0;
}

No comments:

Post a Comment