Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

2011/12/11

Avoid Excessive Retaining Mistake

When I ran "Analyze" on my project, I got a lot of "potential leak" warnings. I thought I was carefully managing object retaining but I did stupid mistakes everywhere.

part of the sample header file
@property (nonatomic, retain) ClassA objA;

part of the sample source file
@synthesize objA;
...
self.objA = [[ClassA alloc] init];
...
// done using objA instance
[self.objA release];

Above example seems good and there is no places for mistake. But actually retaining is happened twice.

  • objA has "retain" attribute
  • it will retain anything with assigning operator ("=")
  • "alloc" method will increase retain count too

    Corrected code
    Class *tmpA = [[ClassA alloc] init];
    self.objA = tmpA;
    [tmpA release];
    ...
    // done using objA instance
    [self.objA release];
    

    Objective-C Singleton Class

    Singleton class is really awesome when I need to share some data throughout many places. If I use normal way which is passing object pointer around, I have to care about a lot of object assigning tasks. With singleton class, it is really simple to use shared class object.

    • no instanciation
    • one class method do the all necessary job
    • first time of the class method call > create single instance
    • other class method calls > return already created instance
    • how to use?
      • include singleton class's header file
      • use class method to obtain class instance

    Sample Class's header file
    @interface SampleClass : NSObject
    
    + (SampleClass*)sharedInstance;
    
    @end
    

    Sample Class's source file
    @implementation SampleClass
    
    static SampleClass *sharedInstance = nil;   // shared instance
    
    + (SampleClass*)sharedInstance
    {
        @synchronized(self)
        {
            if (sharedInstance == nil)
                sharedInstance = [[super allocWithZone:nil] init];
    
            return sharedInstance;
        }
    }
    
    + (id)allocWithZone:(NSZone*)zone
    {
        return [[self sharedInstance] retain];
    }
    
    - (id)copyWithZone:(NSZone*)zone
    {
        return self;
    }
    
    - (id)retain
    {
        return self;
    }
    
    - (NSUInteger)retainCount
    {
        return NSUIntegerMax;  // object cannot be released
    }
    
    - (oneway void)release
    {
        // do nothing
    }
    
    - (id)autorelease
    {
        return self;
    }
    

    Labels

    Followers