Xcode 4.2中ARC中的__weak和autorelease池 [英] __weak and autorelease pool in ARC in Xcode 4.2

查看:102
本文介绍了Xcode 4.2中ARC中的__weak和autorelease池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目使用ARC.我使用以下代码进行了测试:

My project use ARC. I tested with the code below:

NSString __weak *string;
@autoreleasepool {
        string = [NSString stringWithString:@"AAA"];
}

NSLog(@"string: %@", string);

我认为它的输出为:

string: (null)

但实际上输出:

string: AAA

我不明白. __weak的作用是什么?

I don't understand it. What is the effect of __weak?

下面的代码:

NSString __weak *string;
NSString __strong *str;
@autoreleasepool {
    str = [NSString stringWithFormat:@"%@", @"AAA" ];
    string = str;
}

NSLog(@"string: %@", string);

它也输出为:

string: AAA

推荐答案

NSString __weak *string;
@autoreleasepool {
        string = [NSString stringWithFormat:@"%@", @"AAA"];
}

NSLog(@"string: %@", string);

它输出以下所需的内容.

it outputs as the following what you want.

string: (null)

因此

string = [NSString stringWithString:@"AAA"];

string = @"AAA";

未在堆中分配的常量字符串文字.

the constant string literal that is not allocated in the heap.

已编辑

str变量对于自动发布的对象仍然具有很强的参考意义.

str variable has still strong reference for the autoreleased object.

以下代码正是您想要的.

The following code is what exactly you want.

NSString __weak *string;
{
    NSString __strong *str;
    @autoreleasepool {
        str = [NSString stringWithFormat:@"%@", @"AAA" ];
        string = str;
    }
}
NSLog(@"string: %@", string);

还有

NSString __weak *string;
@autoreleasepool {
    NSString __strong *str;
    str = [NSString stringWithFormat:@"%@", @"AAA" ];
    string = str;
}
NSLog(@"string: %@", string);

这篇关于Xcode 4.2中ARC中的__weak和autorelease池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆