Graphics Programs Reference
In-Depth Information
{
// Create an array of three adjectives
NSArray *randomAdjectiveList = [NSArray arrayWithObjects:@"Fluffy",
@"Rusty",
@"Shiny", nil];
// Create an array of three nouns
NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
@"Spork",
@"Mac", nil];
// Get the index of a random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive.
NSInteger adjectiveIndex = rand() % [randomAdjectiveList count];
NSInteger nounIndex = rand() % [randomNounList count];
// Note that NSInteger is not an object, but a type definition
// for "unsigned long"
NSString *randomName = [NSString stringWithFormat:@"%@ %@",
[randomAdjectiveList objectAtIndex:adjectiveIndex],
[randomNounList objectAtIndex:nounIndex]];
int randomValue = rand() % 100;
NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + rand() % 10,
'A' + rand() % 26,
'0' + rand() % 10,
'A' + rand() % 26,
'0' + rand() % 10];
BNRItem *newItem =
[[self alloc] initWithItemName:randomName
valueInDollars:randomValue
serialNumber:randomSerialNumber];
return newItem;
}
This method creates two arrays using the method arrayWithObjects: . This method
takes a list of objects terminated by nil . nil is not added to the array; it just indicates
the end of the argument list.
Then randomItem creates a string from a random adjective and noun, a random integer
value, and another string from random numbers and letters. It then creates an instance of
BNRItem and sends it the designated initializer message with these randomly-created ob-
jects and int as parameters.
In this method, you also used stringWithFormat: , which is a class method of
NSString . This message is sent directly to NSString , and the method returns an
NSString instance with the passed-in parameters. In Objective-C, class methods that re-
Search WWH ::




Custom Search