Do loops and convenience methods cause memory peaks with ARC?

前端 未结 2 406
终归单人心
终归单人心 2021-02-01 08:54

I\'m working with ARC and seeing some strange behavior when modifying strings in a loop.

In my situation, I\'m looping using NSXMLParser delegate callbacks, but I see t

相关标签:
2条回答
  • 2021-02-01 09:03

    While you're hunting memory-related bugs, you should note that @"" and @" Hello" will be immortal objects. You can think about it as a const, but for objects. There will be one, and only one, instance of this object in memory the entire time.

    As @bbum pointed out, and you verified, the @autoreleasepool is the correct way to deal with this in a loop.

    In your example with the @autoreleasepool and NSMutableString, the pool doesn't really do much. The only mortal object inside the loop is your mutableCopy of @"", but that will only be used once. The other case is just an objc_msgSend to a persisting object (the NSMutableString), which only references an immortal object and a selector.

    I can only assume the memory build up is inside Apple's implementation of NSMutableString, although I can wonder why you'd see it inside the @autoreleasepool and not when it's absent.

    0 讨论(0)
  • 2021-02-01 09:13

    You are polluting the autorelease pool with tons and tons of autoreleased objects.

    Surround the internal part of the loop with an autorelease pool:

    for (...) {
        @autoreleasepool {
            ... your test code here ....
        }
    }
    
    0 讨论(0)
提交回复
热议问题