为什么iOS中没有发布弱NSString属性? [英] Why do weak NSString properties not get released in iOS?

查看:106
本文介绍了为什么iOS中没有发布弱NSString属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下示例代码以了解ARC的工作原理

I wrote the following sample code to see how ARC works

@property (nonatomic, weak) NSString *myString;
@property (nonatomic, weak) NSObject *myObj;
@end

@implementation ViewController
@synthesize myString = _myString;
@synthesize myObj = _myObj;
- (void) viewDidAppear:(BOOL)animated
{
    NSLog(@"Appearing Obj: !%@!",self.myObj);
    NSLog(@"Appearing String: !%@!",self.myString);
}

- (void)viewDidLoad
{
    self.myObj = [[NSObject alloc] init];
    self.myString = [[NSString alloc] init];
    NSLog(@"Loading Obj %@",self.myObj);
    NSLog(@"Loading String: !%@!",self.myString);
}

但令人惊讶的是我得到了这些结果:

However surprisingly I got these results:

2012-06-19 15:08:22.516 TESTER[4041:f803] Loading Obj (null)
2012-06-19 15:08:22.517 TESTER[4041:f803] Loading String: !!
2012-06-19 15:08:22.533 TESTER[4041:f803] Appearing Obj: !(null)!
2012-06-19 15:08:22.535 TESTER[4041:f803] Appearing String: !!

正如你所看到的,Obj得到了正确的发布,但我的字符串(也是一个弱的属性)确实不打印出来...为什么不呢?

As you can see, Obj got released properly but my string (which is also a weak property) does not print out null...Why not?

推荐答案

NSString 使用各种内部技巧,以重用对象,避免不必要的分配和副本。它可以这样做,因为 NSString 实例是不可变的。在这种情况下,可能有一个共享实例来表示由 [[NSString alloc] init] 返回的空字符串,并且此共享实例将保留在其他位置单身人士。

NSString uses all sorts of internal trickery to reuse objects and avoid unnecessary allocations and copies. It can do this because NSString instances are immutable. In this case there is probably a shared instance to represent an empty string which is being returned by [[NSString alloc] init], and this shared instance will be retained somewhere else as a singleton.

这篇关于为什么iOS中没有发布弱NSString属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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