Weak、Strong、assign 和 autorelease + 1道面试题

来源:互联网 发布:淘宝店仓库管理制度 编辑:程序博客网 时间:2024/06/13 05:53


一、weak、strong、assign的理解

1. OC 对象用 strong,为什么连线的ui控件却用weak?

controller → view → view.subViews → imageView → 强引用
controller → imageView → 弱引用
controller → imageView 这个位置换成 strong 也可以,但是不建议,如果一个对象被多个对象强引用,当这多个对象中有一个对象忘记释放,那么该对象也不能释放。
ARC环境指定编译文件不使用arc -fno-objc-arc 。
补充:
让程序兼容ARC和非ARC部分:
转变为非ARC  -fno-objc-arc  
转变为ARC  -f-objc-arc 




2.Weak 和 assign的区别

weak 对象释放后指向0地址;
assign 对象释放后指向地址不变,成为野指针;


二、自动释放池

1.MRC内存管理原则:
// 谁申请,谁释放。
// 遇到 alloc / copy / retain,都需要添加 release 或 autorelease。

2. autorelease:
// 添加一个自动释放的标记,会延迟自动释放。
// 当一个autorelease的对象超出了作用域之后,会被添加到最近的自动释放池中。
// 当自动释放池被释放之前,会像池中所有的对象发送release消息,释放池中所有的对象。 

3. iOS开发中的内存管理
(1)在iOS开发中,并没有JAVA或C#中的垃圾回收机制
(2)使用ARC开发,只是在编译时,编译器会根据代码结构自动添加了retainreleaseautorelease

4. 自动释放池的工作原理
(1)标记为autorelease的对象在出了作用域范围后,会被添加到最近一次创建的自动放池
(2)当自动释放池被销毁耗尽时,会向自动释放池中的所有对象发送release消息

5. 自动释放池和主线程 

原文:
The Application Kit creates an
autoreleasepool onthemain threadatthe beginning of every cycle of the event loop, and drains it at theend, thereby releasing anyautoreleased objectsgeneratedwhile 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 temporaryautoreleasedobjects within the event loop, however, it may be beneficial to create “local”autoreleasepools to help to minimize the peak memory footprint. 
在主线程消息循环开始的时候创建了自动释放池,在消息循环结束的时候清掉自动释放池

6.什么时候使用自动释放池 
If youwrite a loop that creates many temporary objects.
You may use an
autoreleasepool block inside the loop to dispose of those objects before the nextiteration. Using anautoreleasepool block in the loop helps to reduce the maximum memory footprint of the application. 
循环中创建了许多临时对象,在循环里面使用自动释放池,用来减少高内存占用。


If youspawn a secondary thread.
You must create your own
autoreleasepool block as soon as the thread begins executing; otherwise, your applicationwill leak objects. (SeeAutoreleasePool Blocks and Threads for details.)

 开启子线程的时候要自己创建自动释放池,否则可能会发生内存泄露。


7.自动释放池常见面试代码

面试题:

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);

        }   

    }











0 0