After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth.
- Connect the iPhone and run the provided project.
- Continuously tap the iPhone screen.
- Observe Memory; it will keep growing.
After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth.
What you’re doing is deeply unsupported, and I strongly recommend that you stop doing it.
In general, Apple doesn’t support folks swizzling methods on Apple’s classes. And in this case you’re swizzling methods on a class, __NSArrayM
, that’s an implementation detail. It’s never good to rely on implementation details because they could change at any time, and that would break your code.
If you explain more about your high-level goal, I may be able to suggest an alternative path forward.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Thank you for your prompt reply and professional advice! I fully understand the risks of directly manipulating the implementation details of private classes, which indeed pose potential issues for code maintenance. The reason I adopted method swizzling is to catch and handle NSRangeException (array out-of-bounds) crashes that commonly occur in iOS apps. Such problems frequently arise in complex business scenarios and severely impact the user experience. For example:
By swapping methods like objectAtIndex:, we’ve implemented unified interception of boundary checks, recording context information and returning default values before an out-of-bounds error occurs. This has effectively reduced the crash rate. However, as you noted, this solution does carry compatibility risks.
I would greatly appreciate your guidance on the following alternative approaches:
Additional Question About Memory Growth:
I've noticed an unexpected memory issue in my test app. When I continuously tap the screen after launch, the memory usage keeps increasing steadily. This happens even when:
Could method swizzling on __NSArrayM interfere with ARC or the autorelease pool? Or might there be hidden retain cycles caused by overriding system methods? I'd appreciate any insights on diagnosing this.
We highly value code quality and compliance, and we look forward to finding a more elegant solution under your guidance. If further details are needed, I’m happy to provide reproduction cases for specific scenarios.
Thank you again for your assistance!