“self” is a four letter word

I don’t like to get strange memory crashes in my applications. So imagine my surprise today when I changed over some CFUUIDRef ivars to NSString, and as a result, I started getting some weird EXC_BAD_ACCESS messages.

For your perusal, consider listing A, where my class is being initialized with a nonatomic and retained property:

@synthesize nameString;
 
- (id)initWithData:(NSString *)inNameString
{
    self = [super init];
 
    if (self)
    {
        nameString = inNameString;
    }
 
    return self;
}

After awhile of beating my head against the wall, I changed it to look more like listing B:

@synthesize nameString;
 
- (id)initWithData:(NSString *)inNameString
{
    self = [super init];
 
    if (self)
    {
        self.nameString = inNameString;
    }
 
    return self;
}

I leave it to the reader to investigate this phenomenon. It is not too complicated, but if the subtlety is lost on you, there is always a memory based crash lurking around the corner.

Needless to say, if you are having strange memory crashes in your application, and your class looks like listing A, change it to look more like listing B. And if your app looks like listing B, it is working fine and you want to see how bad bad can really get, change it to look more like listing A.

Leave a Reply