一、weak、strong、assign的理解
The Application Kit creates an autoreleasepool on themain threadat the beginning of every cycle of the event loop, and drains it at theend, thereby releasing any autoreleased objects generatedwhile processing an event. If you use the Application Kit, youtherefore typically don’t have to create your own pools. If your applicationcreates a lot of temporary autoreleasedobjects within the event loop, however, it may be beneficial to create “local” autoreleasepools to help to minimize the peak memory footprint.
You may use an autoreleasepool block inside the loop to dispose of those objects before the nextiteration. Using an autoreleasepool block in the loop helps to reduce the maximum memory footprint of the application.
You must create your own autoreleasepool block as soon as the thread begins executing; otherwise, your applicationwill leak objects. (See AutoreleasePool Blocks and Threads for details.)
開啓子線程的時候要自己創建自動釋放池,否則可能會發生內存泄露。
面試題:
int largeNumber = 999*9999;
for ( int i = 0; i < largeNumber; ++i ) {
NSString *str = @"Hello World";
str = [str stringByAppendingFormat:@" - %d", i ];
str = [str uppercaseString];
NSLog(@"%@", str);
}
問:以上代碼存在什麼樣的問題?如果循環的次數非常大時,應該如何修改?
答:
int largeNumber = 999*9999;
for (int i = 0; i < largeNumber; ++i) {
@autoreleasepool {
NSString *str = @"Hello World";
str = [str stringByAppendingFormat:@" - %d", i];
str = [str uppercaseString];
NSLog(@"%@", str);
}
}