'self' in class methods


I completely understand the use of self in class methods such that: id someObject = [self alloc] init];

My question takes this idea a step further as it pertains to subclassing and overriding a class method. I subclassed Possession and wanted to know if the code following is appropriate and acceptable practice in the community.

I understand I have memory management issues, my code merely reflects the knowledge up to this point in the book

I first created a subclass of Possession which I called BallGlove

#import "Possession.h"

@interface BallGlove : Possession
    NSString *brandName;

-(void)setBrandName:(NSString *)name;
-(NSString *)brandName;


Next, I implemented my setter / getter as well as overrode the +randomPossession method I inherited (and -description method).

#import "BallGlove.h"

@implementation BallGlove

    BallGlove *myGlove = [super randomPossession];
    NSArray *brandNames = [NSArray arrayWithObjects:@"Rawlings", @"Mizuno", @"Wilson", nil];
    unsigned long randomNameIndex = rand() % [brandNames count];
    [myGlove setBrandName:[brandNames objectAtIndex:randomNameIndex]];
    NSLog(@"myGlove is of type class: %@", [self class]);
    return myGlove;

-(void)setBrandName:(NSString *)name
    brandName = name;
-(NSString *)brandName
    return brandName;

-(NSString *)description
    return [NSString stringWithFormat:@"%@ // brand name: %@", [super description], [self brandName]];

The setter/getter is self-explanatory. The description merely creates a string from my superclass’ description and the brand name of my object.

My real question involves overriding the +randomPossession method. My output demonstrates that the returned instance from overriding is in fact a BallGlove instance. However, I was curious if the manner in which I overrode is appropriate (i.e. parallel the -init format and catch the superclass’ implementation in a variable of the desired class - BallGlove - and then add your customization to the variable which you subsequently return).

Thanks in advance for the input!



So, what happens is this:

You send +randomPossession to the class BallGlove. Therefore, self is the class BallGlove. When +[Possession randomPossession] is called, self is still BallGlove because super points to self (the difference in keywords only matters for the method lookup). Thus, in +[Possession randomPossession], [self alloc] sends alloc to BallGlove.