Why do weak NSString properties not get released in iOS?

偶尔善良 提交于 2019-11-27 09:19:58

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.

[[NSString alloc] init] always returns identical value. 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. 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.

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)

-(id)init
{
    return SOME_CONSTANT_VALUE;
}

It might be kCFEmptyString, but I'm not sure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!