0

I have created two classes (FirstClass and SecondClass) in command line application. I created an object of SecondClass in FirstClass method. Now I want to call that method in main and release the memory allocated to that object. My code is as follows..

@implementation FirstClass

+(NSMutableArray *) addObject{
    NSMutableArray *namesArray = [[[NSMutableArray alloc]init] autorelease];
    SecondClass *second = [[SecondClass alloc]init];
    NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1
    [second setName:@"Mobicule"];
    [namesArray addObject:second];
    NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2
    [second release];
    NSLog(@"After release, count = %ld",[second retainCount]); //RC = 1
    return namesArray;
}

@end

I want to make retain count to zero..

And main function is as follows..

int main (int argc, const char * argv[]) {

@autoreleasepool {

    // insert code here...
   // NSLog(@"Hello, World!");

    NSMutableArray *arrayMain = [[NSMutableArray alloc]init];

    arrayMain = [FirstClass addObject];

    for (int i = 0; i<[arrayMain count]; i++) {

        NSLog(@"%@",[[arrayMain objectAtIndex:i] name]);
    }

   NSLog(@"%ld",[arrayMain retainCount]);

}
return 0;
}
Andreas
  • 2,332
  • 1
  • 16
  • 20
user1468310
  • 1
  • 1
  • 2
  • By definition, retainCount cannot return 0. One of the numerous reasons why it is useless. – bbum Jun 30 '12 at 19:33

1 Answers1

0

I am assuming your synthesised property for name is retain.

  +(NSMutableArray *) addObject{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *namesArray = [[NSMutableArray alloc]init];
    SecondClass *second = [[[SecondClass alloc]init]autorelease];
    NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1
    [second setName:@"Mobicule"]; //implementation will handle the release for you
    [namesArray addObject:second];
    NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2
    [pool release];
    NSLog(@"After pool release, count = %ld",[second retainCount]); //RC=1
    return [namesArray autorelease];
}  

You should never use -retainCount, because it never tells you anything useful.

Take a look at When to use -retainCount?

Community
  • 1
  • 1
Parag Bafna
  • 22,143
  • 7
  • 65
  • 138