ssgreg
ssgreg

Reputation: 588

ARC is enabled. Why the 'dealloc' method doesn't call?

ARC is enabled. Why the 'dealloc' method doesn't call? Should I use @autoreleasepool here or not? Why? Thank you.

@interface Test : NSObject
@end

@implementation Test

+(id)testFromNothing
{
  id res = [Test alloc];
  return res;
}

-(void)dealloc
{
  NSLog(@"deallocated");
}

@end


int main(int argc, const char * argv[])
{
  Test* test = [Test testFromNothing];
  return 0;
}

Upvotes: 1

Views: 285

Answers (1)

justin
justin

Reputation: 104698

Yes, you should use autorelease pool in main. Another problem is that you are not initializing your object in testFromNothing.

Reason: You should create autorelease pools wherever a thread is entered (including the main thread). Of course, if that thread just uses C code, then no objc objects will be autoreleased, so it is unnecessary in those scenarios.

Regarding the "Why?" -- ARC also uses the autoreleasing and expects autorelease pools are always in place. Programs need to support autorelease semantics correctly since ARC also assumes it may use autorelease pools, and it is the programmer's responsibility to set up the autorelease pools correctly (in some contexts). ARC is unlike GC, and very similar to MRC regarding the reference count operations and the sequence in which the reference count operations occur. With GC, several collection schemes may be used (e.g. you can see a lot of growth before collection, or collection could happen on secondary threads), but ARC operates similar to well structured retain/release/autorelease operations -- plus a few tricks/extensions.

Upvotes: 5

Related Questions