OC語言day06-02-1自動釋放池大對象問題

pragma mark 自動釋放池大對象問題

pragma mark 概念

pragma mark 代碼

AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    return YES;

}

@end


ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

ViewController.m

#import "ViewController.h"

#import "Person.h"

@interface ViewController ()



@end



@implementation ViewController



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

#warning 1. 不要在自動釋放池中使用比較消耗內(nèi)存的對象,占用內(nèi)存比較大的對象

    /*

    @autoreleasepool {

        Person *p = [[[Person alloc]init]autorelease];

        

        

        // 假如p 對象只在100行的地方使用, 以后都不用了

        

        // 一萬行代碼

    }

     */

    

#warning  2. 盡量不要再自動釋放池中使用循環(huán), 特別是循環(huán)的次數(shù)非常多,并且還非常占用內(nèi)存

    /*

    @autoreleasepool {

        

        for (int i = 0; i < 99999; ++i) {

            //每調(diào)用一次都會創(chuàng)建一個新的對象

            // 每個對象都會占用一塊存儲空間

            Person *p = [[[Person alloc]init]autorelease];

        }

    }// 只有執(zhí)行到這一行,所有的對象才會被釋放

     */

    

#warning  3.解決創(chuàng)建多個對象占用內(nèi)存的問題

    /*

    for (int i = 0; i<99999; ++i) {

        @autoreleasepool {

            Person *p = [[[Person alloc]init]autorelease];

        }

    }// 執(zhí)行到這一行, 自動釋放池就釋放了

     */

    NSLog(@"------------------------");

}



@end



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容