gpt4 book ai didi

iphone - 为什么弱 NSString 属性没有在 iOS 中发布?

转载 作者:可可西里 更新时间:2023-11-01 04:08:58 24 4
gpt4 key购买 nike

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

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

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

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 已正确释放,但我的字符串(这也是一个弱属性)没有打印出 null...为什么不呢?

最佳答案

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

关于iphone - 为什么弱 NSString 属性没有在 iOS 中发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11107729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com