Taking the randomName a bit farther


As I watched RandomPossessions create these lists of items with random adjectives and nouns, it reminded me of loot dropped in an RPG, so I decided to take it a bit farther. I added a random descriptor for each name, so now I have items named “Adjective Noun of Descriptor” which ends up looking like “Melancholy Parsnip of Flatulence” or “Blessed Chaps of Lunching” for an example.

I used this as a way to test myself to see if I truly understood how things were working, and it worked! For other newbies like myself, here’s what my code looks like:

+ (id)randomPossession
    // Create three arrays with a list of possible adjectives, nouns, and descriptors.
    // Note: When using NSArray's arrayWithObjects:, you can pass as many
    // objects as you like. At the end of that list, you put nil to
    // signify that there are not more objects - otherwse you will crash.
    // The nil vally is not added to the array, but it is used by the method
    // to determine the end of the list.
    NSArray *randomAdjectiveList = [NSArray arrayWithObjects:@"Fluffy",
    NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
    NSArray *randomDescriptorList = [NSArray arrayWithObjects:@"Pain",
                                     @"OH SHI...",
    // 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, in this case.
    int adjectiveIndex = random() % [randomAdjectiveList count];
    int nounIndex = random() % [randomNounList count];
    int descriptorIndex = random() % [randomDescriptorList count];
    NSString *randomName = [NSString stringWithFormat:@"%@ %@ of %@",
                            [randomAdjectiveList objectAtIndex:adjectiveIndex],
                            [randomNounList objectAtIndex:nounIndex],
                           [randomDescriptorList objectAtIndex:descriptorIndex]];
    int randomValue = random() % 100;
    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
                                    '0' + random() % 10,
                                    'A' + random() % 26,
                                    '0' + random() % 10,
                                    'A' + random() % 26,
                                    '0' + random() % 10];
    // Once again, ignore the memory problems with this method
    // We use "self" instead of the name of the class in class methods...
    // Keep reading to find out why
    Possession *newPossession = 
        [[self alloc] initWithPossessionName:randomName
    return [newPossession autorelease];

I thought it was mildly amusing, and hoping that this gives other inexperienced Objective-C guys (like me) a reason to try something new.


This is great. There is no better way to learn than experimenting on top of working examples.