Chp 3 Challenge Solution

Thursday, September 15, 2005

As promised I'm going to systematic answer each solution within the Cocoa Programming for Mac OS X.

The first part was just to add a format to the calendar date entry.

While the second just loops through the array to remove the items manually, and noticing that the item gets deallocated due to the retain count reaching 0.

Here's the adapted main method from the challenge at the end of chapter 3.

int main (int argc, const char * argv[]) {
NSMutableArray *array;
int i;

LotteryEntry *newEntry;
LotteryEntry *entryToPrint;

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSCalendarDate *now = [[NSCalendarDate alloc] init];
srandom(time(NULL));
array = [[NSMutableArray alloc] init];
for (i = 0 ; i < 10 ; i++ ) {
newEntry = [[LotteryEntry alloc] initWithEntryDate:
[now dateByAddingYears:0
months:0
days:(i*7)
hours:0
minutes:0
seconds:0]];

// Answer to part I of the challenge
// Tokens below are listed in Table 3.2 on pg 72
[newEntry setCalendarDateFormat:@"%b, %d %Y"];
[array addObject:newEntry];
[newEntry release];
}

for ( i = 0 ; i < 10 ; i++ ) {
entryToPrint = [array objectAtIndex:i];
NSLog(@"entry %d is %@", i , entryToPrint);
}

//This loop is the solution to the second part of the challenge
//Its removing each item one at a time
for ( i = 0 ; i < 10 ; i++ ) {
NSLog(@"removing item %d",i);
[array removeObjectAtIndex:0];
}

[array release];
[now release];
[pool release];
return 0;
}

Comments: Post a Comment


<< Home

This page is powered by Blogger. Isn't yours?