[英]Why do weak NSString properties not get released in iOS?
I wrote the following sample code to see how ARC works我写了下面的示例代码来看看 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);
}
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: !!
As you can see, Obj got released properly but my string (which is also a weak property) does not print out null...Why not?如您所见,Obj 已正确释放,但我的字符串(这也是一个弱属性)没有打印出 null ......为什么不呢?
NSString
uses all sorts of internal trickery to reuse objects and avoid unnecessary allocations and copies. NSString
使用各种内部技巧来重用对象并避免不必要的分配和复制。 It can do this because NSString
instances are immutable.它可以这样做,因为
NSString
实例是不可变的。 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.在这种情况下,可能有一个共享实例来表示由
[[NSString alloc] init]
返回的空字符串,并且这个共享实例将作为单例保留在其他地方。
[[NSString alloc] init]
always returns identical value. [[NSString alloc] init]
总是返回相同的值。 You can check it by yourself.你可以自己检查一下。
NSString *string1 = [[NSString alloc] init];
NSString *string2 = [[NSString alloc] init];
NSString *string3 = [[NSString alloc] init];
NSLog(@"string1 = %p, string2 = %p, string3 = %p", string1, string2, string3)
This code returns three identical addresses.此代码返回三个相同的地址。 In my case, output was:
就我而言,输出是:
string1 = 0x3e8dd74c, string2 = 0x3e8dd74c, string3 = 0x3e8dd74c
That means [[NSString alloc] init]
returns Singleton .这意味着
[[NSString alloc] init]
返回Singleton 。 Singletons usually can't be released.单身人士通常不能被释放。
Making strings with other methods (like initWithFormat:
) makes usual 'non-singleton' objects, which usually can be released , with some exceptions.使用其他方法(如
initWithFormat:
)生成字符串会生成通常的“非单例”对象,这些对象通常可以被释放,但有一些例外。
Further: Looking source code (Assembler):进一步:查看源代码(汇编程序):
-[NSPlaceholderString init]:
00040ea4 f64b009c movw r0, 0xb89c
00040ea8 f2c00016 movt r0, 0x16
00040eac 4478 add r0, pc
00040eae 4770 bx lr
it would be something like this (in objectiveC)它会是这样的(在objectiveC中)
-(id)init
{
return SOME_CONSTANT_VALUE;
}
It might be kCFEmptyString
, but I'm not sure.它可能是
kCFEmptyString
,但我不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.