Autorelease pool

  • View
    808

  • Download
    3

Embed Size (px)

DESCRIPTION

 

Text of Autorelease pool

  • 1. Autorelease PoolMichael Pan13527
  • 2. -(NSString *) name{NSString * name= [[NSString alloc]initWithString:@Bob];return name;}Memory leak!!!iOS 413527
  • 3. -(NSString *) name{NSString * name= [[NSString alloc]initWithString:@Bob];[name release]; // ??return name;}iOS 413527
  • 4. -(NSString *) name{NSString * name= [[NSString alloc]initWithString:@Bob];return name;[name release]; // ??}iOS 413527
  • 5. -(NSString *) name{NSString * name= [[NSString alloc]initWithString:@Bob];[name autorelease];return name;}NSString * outer = [customer name];[outer retain];//....[outer release];iOS 413527
  • 6. -(NSString *) name{NSString * name= [[NSString alloc]initWithString:@Bob];// [name autorelease];return name;}ARC13527
  • 7. Name does matter begin with alloc/new/copy/mutableCopy will not be putinto autorelease pool others will add object into autorelease pool automatically-(id) newCar;13527
  • 8. Demo ARCDemo13527
  • 9. Pool [obj autorelease] class level constructor [obj release] [pool drain] event loop autorelease pool retainNO Arc13527
  • 10. Pool NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init]; poolstack autoreleasepool pool drain pool drainpool1pool2int main(){NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init];NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];}NO Arc13527
  • 11. RecapNSMutableString * s1 = [[NSMutableString alloc] initWithString:@"hello"];NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init];NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];!NSArray * staticArray = [NSArray arrayWithObject:s1];NSLog(@"s1 retain count is %lu", [s1 retainCount]);[pool1 drain];NSLog(@"s1 retain count is %lu", [s1 retainCount]);Result is ?pool2pool1staticArrays1iOS 413527
  • 12. Poolint main(){@autoreleasepool{//...}}iOS 513527
  • 13. Clean pool nicelyint i;for (i = 0; i < 1000000; i++) {id object = [someArray objectAtIndex: i];NSString *desc = [object description];// and do something with the description}NSAutoreleasePool *pool;pool = [[NSAutoreleasePool alloc] init];int i;for (i = 0; i < 1000000; i++) {id object = [someArray objectAtIndex: i];NSString *desc = [object description];// and do something with the descriptionif (i % 1000 == 0) {[pool drain];pool = [[NSAutoreleasePool alloc] init];}}[pool release]iOS 413527
  • 14. Clean pool nicelyint i;for (i = 0; i < 1000000; i++) {id object = [someArray objectAtIndex: i];NSString *desc = [object description];// and do something with the description}int i;for (i = 0; i < 1000000; i++) {@autoreleasepool{id object = [someArray objectAtIndex: i];NSString *desc = [object description];// and do something with the description}}iOS 513527
  • 15. EqualNSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];[obj autorelease];[pool drain];@autoreleasepool{id __autoreleasing obj2;obj2 = obj;}ARCno ARC13527