Do loops and convenience methods cause memory peaks with ARC?

前端 未结 2 695
你的背包
你的背包 2021-02-01 08:39

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:01

    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.

提交回复
热议问题