3. objC内存管理
NSAutoreleasePool* pool= [[NSAutoreleasePoolalloc] init]; Patient* tempPat = [[PaitentCreatorCreatePatient] retain]; NSLog(@"the tempPat instance object retain count = %ld", [tempPat retainCount]);//2 /** */ NSMutableString* pString = [[NSMutableStringalloc]initWithString:@"Zhao^Tiegui^^^"]; NSLog(@"the current name retain count = %ld",[pString retainCount]);//1 tempPat.name = pString; NSLog(@"the current name retain count = %ld",[pString retainCount]);//2 [pString release]; NSLog(@"the current name retain count = %ld",[pString retainCount]);//1 [tempPat printOut]; /** */ NSString* tempSex = [[NSStringalloc] initWithCString:"Zhao^Tiegui"]; NSLog(@"the sex sex retain count = %ld",[tempSex retainCount]);//1 tempPat.sex = tempSex; NSLog(@"the sex sex retain count = %ld",[tempSex retainCount]);//2 [tempSex release]; NSLog(@"the sex sex retain count = %ld",[tempSex retainCount]);//1 [tempPat printOut]; NSLog(@"the tempPat retain count = %ld",[tempPat retainCount]);//2 [tempPat release]; NSLog(@"the tempPat retain count = %ld",[tempPat retainCount]);//1 [pool release]; NSLog(@"the pool retain count = %ld",[pool retainCount]);//1 NSLog(@"the tempPat retain count = %ld",[tempPat retainCount]);//1152921504606846975无效的值 [tempPat printOut];//产生异常
这里要特别的注意,在新建的类中,一定要重载dealloc函数。并且,super的dealloc要放在子类释放之后,这里和C++析构的顺序是相同的。具体原因一样,子类在析构时候,可能会调用父类的函数。所以,父类一定要后析构于子类。