简体   繁体   中英

Objective-C NSString memory leak with objc_setAssociatedObject

I found a memory leak for NSString with objc_setAssociatedObject

Test Code:

int i = 0;
while (YES) {
    @autoreleasepool {
        NSString *string = [[NSString alloc] initWithFormat:@"%d", i];
        // Comment this line. Then the memory leak is gone.
        objc_setAssociatedObject(string, "key", [[NSObject alloc] init], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    i++;
}

NSObject can't release. Not sure for NSString .

If I comment the code objc_setAssociatedObject(string, "key", [[NSObject alloc] init], OBJC_ASSOCIATION_RETAIN_NONATOMIC); . There is no memory leak.

Does anyone know what happened?

Maybe related to Tagged Pointer Strings

Tagger Pointer Strings are actually invalid 64 bit pointers where the content is stored within the pointer itself

this helps prevent unnecessary memory allocation

They are invalid pointers in the sense that they don't point to any real memory value

"""Objects are aligned in memory, such that their address is always at least a multiple of the pointer size, and in practice typically a multiple of 16. Object pointers are stored as a full 64-bit integer, but this alignment means that some of the bits will always be zero.

Tagged pointers take advantage of this fact to give special meaning to object pointers where those bits are not zero. In Apple's 64-bit Objective-C implementation, object pointers with the least significant bit set to one (which is to say, odd numbers) are considered tagged pointers. Instead of doing the standard isa dereference to figure out the class, the next three bits are considered as an index into a tagged class table. This index is used to look up the class of the tagged pointer. The remaining 60 bits are then left up to the tagged class to use as they please.""" This is a beautiful hack.

I think for NSTaggedPointerString teh associated objects might be getting cleared in the next runloop

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM