IOS abnormal flash back protection method and readable storage medium

By using the Runtime mechanism to intercept and exchange system-like methods in iOS applications, the protection SDK is designed, real-time protection and reporting crash logs are solved, and the passivity and information loss problems of traditional protection solutions are achieved, and the global and non-invasive protection effect is achieved to ensure the stability of the app and rapid repair.

CN120523631APending Publication Date: 2025-08-22HANGZHOU ROBAM APPLIANCES CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202510608161.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-05-13
Publication Date
2025-08-22

AI Technical Summary

Technical Problem

When iOS applications face complex and changeable boundary scenarios during operation, traditional protection solutions have high passivity and require manual protection codes, which are difficult to fully protect. The crash log reports depend on callbacks after crashes, which has a high risk of information loss, resulting in a long repair cycle.

Method used

The Runtime mechanism is used to intercept and exchange system-like methods, and the independent protection logic is designed to encapsulate it as a protection SDK, intercept crash scenarios in real time and collect logs to achieve global and non-invasive protection, and combine the real-time reporting of crash logs to form a closed-loop process.

Benefits of technology

It realizes systematic and non-invasive protection, significantly reduces the App crash rate, ensures that developers can accurately locate the cause of the crash, is compatible with all iOS versions, comply with audit specifications, avoids information loss, and shortens the repair cycle.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120523631A_ABST
    Figure CN120523631A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of iOS application programs, in particular to an iOS abnormal flash back protection method and a readable storage medium. The method comprises the following steps: designing independent protection logics for different types of crash scenes, and uniformly packaging the independent protection logics into a protection SDK (Software Development Kit); implanting the protection SDK into the App so as to run the protection SDK when the APP is started; when the protection SDK is operated, a Runtime mechanism is adopted to intercept and exchange system class methods so as to realize real-time protection of an application layer, and the App continues to be operated after exchange; and completing crash log collection and reporting crash log information in the same intercepted execution process. Therefore, systematic, non-intrusive and information-traceable protection is achieved, and it is ensured that developers can accurately position crash reasons while App flash quit is effectively avoided.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the technical field of iOS application programs, and in particular to an iOS abnormal flash back protection method and a readable storage medium. Background Art

[0002] The issue of unexpected crashes in iOS applications (APPs) has always been a top priority during development. While these crashes can be addressed immediately upon discovery during routine development, they require manual repairs before releasing a new version. During this manual repair process, these crashes can lead to business losses, including interruptions to key APP services, decreased user retention, diminished brand reputation, and reduced lifetime value.

[0003] To address this, protection solutions for app crashes (such as try-catch solutions or localized protection solutions) have emerged. However, iOS apps still face complex and ever-changing edge cases in real-world operation. Traditional solutions are relatively passive, requiring manual implementation of protection code for each crash point. Even existing protection systems that utilize security-based monitoring mechanisms are limited to single-point protection during the development phase (static code inspection), message forwarding, or runtime. This approach is mostly preventative, making security checks at the time of use. However, a large amount of data is returned by backend interfaces, and many data values ​​are directly used during use without security checks or outside the scope of security checks. This still makes it difficult to prevent app crashes and creates the risk of omissions. Furthermore, because the process is terminated by the system after a crash, crash log reporting in existing technologies often relies on callbacks after the crash occurs, making it difficult to record critical on-site logs and posing a significant risk of information loss. This makes it difficult for developers to accurately identify the root cause, resulting in longer repair cycles and further amplified business losses. Therefore, providing a comprehensive, non-intrusive, and traceable protection solution is inherently challenging. Summary of the Invention

[0004] In response to the above technical problems, the present invention proposes an iOS abnormal crash protection method and readable storage medium, aiming to achieve systematic, non-invasive and information-traceable protection, while effectively preventing App crashes and ensuring that developers can accurately locate the cause of the crash.

[0005] In a first aspect, the present application provides a method for preventing iOS from crashing due to abnormalities, comprising the following steps:

[0006] Design independent protection logic for different types of crash scenarios and package them into a protection SDK;

[0007] Embed the protection SDK into the App to run the protection SDK when the App is launched;

[0008] When running the protection SDK, the runtime mechanism is used to intercept and exchange system class methods to achieve real-time protection at the application layer, and the App continues to run after the exchange;

[0009] Complete crash log collection and report crash log information in the same execution process of interception.

[0010] In some embodiments, independent protection logic is designed for different types of crash scenarios, including:

[0011] For crash scenarios that require protection, create categories for corresponding system classes and define protection methods for the corresponding system classes in each category.

[0012] In some embodiments, a runtime mechanism is used to intercept and exchange system class methods to achieve real-time protection at the application layer, including:

[0013] Use the Runtime mechanism to obtain the original methods and protection methods of system classes;

[0014] Intercept the system class methods corresponding to each category, and use Method Swizzling to swap the original method of the system class with the protection method to achieve crash and flash back protection.

[0015] In some embodiments, swapping a system class's original method with a guarded method includes:

[0016] The original method of the system class is exchanged with the guard method, and the dispatch_once thread safety mechanism is implemented to ensure that the exchange operation is performed only once.

[0017] In some embodiments, the crash scenarios include unrecognized selector, container out of bounds, KVOCrash, NSTimer circular reference, NSNull value processing, and non-main thread UI operations.

[0018] In some embodiments, if the crash scenario corresponding to the classification is an unrecognized selector, a protection method corresponding to the system class is defined in the classification, including:

[0019] When an object receives an unimplemented method call, the original method of the system class executes the message query, dynamic parsing, and backup receiver search processes in sequence. If none of the three processes are processed, the following steps are executed:

[0020] Determine whether the object has a corresponding method implementation. If so, return the original method signature. If not, construct a method signature with a void return value and return it.

[0021] Generate an NSInvocation instance based on the method signature to encapsulate the method call information and enter the final step of message forwarding for processing.

[0022] In some embodiments, if the crash scenario corresponding to the category is NSTimer circular reference, a protection method for the corresponding system class is defined in the category, including:

[0023] Create a timer entry method;

[0024] When starting the app, intercept all timer instantiation requests and swap the created timer entry method;

[0025] Define the abstract intermediate class KJProxyProtector;

[0026] In the swapped methods, the NSTimer instance has a strong reference to the KJProxyProtector, which in turn has a weak reference to the native target.

[0027] In some embodiments, if the crash scenario corresponding to the classification is a non-main thread UI operation, a protection method for the corresponding system class is defined in the classification, including:

[0028] When the app is started, the core layout methods of UIView are intercepted and exchanged. The core layout methods of UIView include setNeedsLayout, layoutIfNeeded, layoutSubviews, and setNeedsUpdateConstraints.

[0029] In the swapped method, it is detected whether the current thread is the main thread. If a non-main thread call is detected, the interception is triggered and the UI operation code block is asynchronously dispatched to the main thread queue for execution. If it is detected that the current thread is already the main thread, the original method is directly called.

[0030] In some embodiments, the crash log information includes an interception occurrence timestamp, a crash scenario type, device information, crash stack information, and a service context. Reporting the crash log information includes:

[0031] Transfer crash log information from the protection SDK to the main App program;

[0032] The main app program uploads the crash log information to a cloud server or a third-party platform.

[0033] In a second aspect, the present application provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements an iOS abnormal crash protection method as described above.

[0034] The beneficial technical effects of the present invention include at least: adopting an iOS abnormal crash protection method and a readable storage medium, constructing an application-level protection layer through dynamic interception and exchange, truly realizing systematic, non-intrusive, user-imperceptible and information-traceable protection, significantly reducing the App crash rate while ensuring that developers can accurately locate the cause of the crash, forming a complete abnormal monitoring-protection-reporting closed-loop process. Specifically, on the one hand, traditional solutions are relatively passive and require manual addition of protection code for each crash point. Even the protection systems currently available on the market that use monitoring mechanisms designed with security judgments are mostly limited to single-point protection during the development stage (static code inspection), message forwarding stage, or runtime. This processing method is mostly preventive and makes security judgments during use. However, a large amount of data is returned by the background interface. During use, many data values ​​are directly used without making security judgments or are not within the scope of security judgments. It is still difficult to avoid the problem of App abnormal crashes and there is a risk of omissions. To this end, this application uses a classified design to add protection methods to system classes without modifying the original class code, cooperates with the Runtime full-link method interception system, and directly executes protection method exchanges locally without modifying the original code. It can intercept exceptions in real time and dynamically repair execution logic at the moment of crash. After the crash is intercepted, the application continues to run, realizing global dynamic protection without modifying the source code, covering all code paths, and achieving an organic combination of static and dynamic protection. It not only overcomes the protection points missed during the development stage, but also avoids the intrusion of traditional Try-Catch into the code structure, so that users can remain responsive when encountering crash scenarios and complete exception repair without noticing. Moreover, unlike the performance loss that may be introduced by existing code rewriting, this application uses a Runtime-based interception mechanism to ensure that the normal process executes the original method without additional overhead. The interception and exchange protection logic is only triggered in exceptions, with extremely low resource usage. It is based on the standardized implementation of Runtime and is compatible with all iOS versions. There is no need to adapt to system upgrades, no private APIs are involved, and it complies with App Store review specifications to ensure compliance (for example, hot fixes are prohibited by Apple).On the other hand, traditional log reporting relies on callbacks after a crash occurs, resulting in incomplete information and inability to associate protection scenarios. Traditional crash logs also have technical problems such as reliance on symbol table parsing, collection lags, and inability to locate context. The present application intercepts and exchanges system-like methods that are prone to crashes through the entire Runtime chain, allowing the protection method to take over the execution process at the moment the crash occurs, thereby creating an execution opportunity for log collection. It is understandable that if the crash process is not intercepted through Runtime, log collection will not be able to execute due to process termination. Only by intercepting the crash can crash log collection be completed in the same execution process, making the integrity of log records possible. Therefore, the present application can embed log collection logic in the protection logic to ensure that crash information is completely preserved and realize real-time reporting of structured crash logs triggered by protection. Crash protection and log reporting form a closed loop to fill the gap between protection blind spots in the development stage and protection capabilities during online runtime, avoiding information loss caused by process termination in traditional crash capture solutions, and enabling developers to accurately locate the root cause of the problem through real-time reported crash logs, achieving the technical effect of "1+1>2".

[0035] Other features and advantages of the present invention will be disclosed in detail in the following specific embodiments and drawings. BRIEF DESCRIPTION OF THE DRAWINGS

[0036] The present invention will be further described below with reference to the accompanying drawings:

[0037] Figure 1 This is a flowchart of a method for preventing iOS from abnormal crashes according to an embodiment of the present invention. DETAILED DESCRIPTION

[0038] The following is an explanation and description of the technical solutions of the embodiments of the present invention in conjunction with the drawings of the embodiments of the present invention. However, the following embodiments are only preferred embodiments of the present invention and are not exhaustive. Based on the embodiments in the implementation manner, other embodiments obtained by those skilled in the art without creative work are all within the scope of protection of the present invention.

[0039] In the following description, terms such as "inside", "outside", "up", "down", "left", "right", etc. that indicate directions or positional relationships are only used to facilitate the description of the embodiments and simplify the description, and do not indicate or imply that the device or element referred to must have a specific direction, be constructed and operate in a specific direction. Therefore, they should not be understood as limiting the present invention.

[0040] Example 1:

[0041] Please see the attached Figure 1 , Figure 1 A flowchart of an iOS abnormal crash protection method provided by an embodiment of this specification is shown.

[0042] like Figure 1 As shown, the iOS abnormal crash prevention method may include at least the following steps:

[0043] Step 101: Design independent protection logic for different types of crash scenarios and encapsulate them into a protection SDK.

[0044] The protection SDK (Software Development Kit) in this embodiment includes a code library of protection logic.

[0045] It can be understood that, unlike local protection solutions, this embodiment provides out-of-the-box stability assurance through SDK design and can be applied to complex App environments.

[0046] Furthermore, in this embodiment, independent protection logic is designed for different types of crash scenarios, including:

[0047] For crash scenarios that require protection, create categories for corresponding system classes, and define protection methods for the corresponding system classes in each category to provide a carrier for subsequent method exchange.

[0048] Category is a syntax feature of Objective-C that allows adding new methods to existing classes (such as system classes NSArray and NSDictionary) without modifying the system class source code.

[0049] This embodiment creates categories for system classes that are prone to crashes. When adding new crash protection types (such as network request timeouts), it is only necessary to add corresponding categories and define protection methods without refactoring existing code, thereby achieving modular on-demand expansion.

[0050] Step 102: embed the protection SDK into the App so that the protection SDK runs when the App is started.

[0051] Specifically, in this embodiment, the protection SDK is implemented by loading the protection SDK using the +load method or initialization function during the app startup phase, providing an operating environment for subsequent method interception. When running the protection SDK, the SDK dynamically detects pre-set system classes prone to crashes, including their class names and method names.

[0052] Step 103: When running the protection SDK, the Runtime mechanism is used to intercept and exchange the system class methods to achieve real-time protection of the application layer, and the App continues to run after the exchange.

[0053] Among them, the Runtime mechanism is the dynamic feature of Objective-C, which allows classes, methods, objects, etc. to be modified at runtime.

[0054] This embodiment implements protection logic injection through collaborative design classification and method exchange, directly intercepts and exchanges system class methods without inheriting or modifying the original class code of the system class, and is compatible with iOS version upgrades, thereby achieving truly non-invasive protection.

[0055] Specifically, in this embodiment, the Runtime mechanism is used to intercept and exchange system class methods to achieve real-time protection at the application layer, including:

[0056] Step 1031: Use the Runtime mechanism to obtain the original method and protection method of the system class.

[0057] For example, in this embodiment, the original method (originalMethod) and the protected method (swizzledMethod) can be obtained through class_getInstanceMethod.

[0058] Step 1032: intercept the system class methods corresponding to each category, and use Method Swizzling to swap the original method of the system class with the protection method to achieve crash and flash back protection.

[0059] The system methods corresponding to each category are crash-prone system methods that require protection. Method Swizzling is a technique that swaps the implementation (IMP) and selector (SEL) of two methods at runtime, replacing the original system method with a custom method.

[0060] Among them, in this embodiment, for class clusters such as NSArray / NSDictionary, it is necessary to locate the actual subclass (such as _NSArrayI) through objc_getClass and perform method exchange to ensure that the protection logic is effective.

[0061] It can be understood that in the category (Category) of the system class prone to crash, the original method and the protection method can be exchanged through the method_exchangeImplementations function in this embodiment, so that when the original system method is called, the logic of the protection method is actually executed without modifying the original code. Specifically, this embodiment intercepts the system method that is prone to abnormal flash backs through MethodSwizzling, so as to swap the selector (SEL, a unique identifier representing the method name) and IMP (a function pointer pointing to the specific implementation of the method) of the original method of the system with the protection method. Since the protection operation has been pre-added in the replacement method, the purpose of avoiding crashes and repairing abnormal flash backs is achieved. Simply put, when an APP crashes abnormally, the protection SDK will execute the exchanged code through method exchange to ensure that the APP does not crash or flash back. After the crash is intercepted, the application continues to run, and the crash log information can also be captured and transmitted. This process is imperceptible to the user and will not cause any impact on the user.

[0062] Furthermore, in this embodiment, the original method of the system class is exchanged with the protection method, including:

[0063] The original method of the system class is exchanged with the guard method, and the dispatch_once thread safety mechanism is implemented to ensure that the exchange operation is performed only once to prevent recursive calls.

[0064] Among them, dispatch_once is a thread safety mechanism provided by GCD (Grand Central Dispatch), which ensures that the code block is executed only once during the life cycle of the program.

[0065] This embodiment implements thread-safe processing through dispatch_once to prevent logical confusion caused by repeated exchange methods in a multi-threaded environment.

[0066] Step 104 : Complete the crash log collection and report the crash log information in the same execution process of the interception.

[0067] Among them, these crash log information can be uploaded to the cloud server or to a third-party platform (such as Tencent Bugly) for analysis and processing, so that developers can fix the crash problem offline based on the log information and update the repaired program code in the APP version iteration.

[0068] Furthermore, in this embodiment, the crash log information includes the interception occurrence timestamp, crash scenario type, device information (such as model, system version, memory status, etc.), crash stack information, and business context (such as the current user operation path). Reporting the crash log information includes:

[0069] Transfer crash log information from the protection SDK to the main App program;

[0070] The main app program uploads the crash log information to a cloud server or a third-party platform.

[0071] The crash log information reported in this embodiment includes a snapshot of the runtime environment, which helps developers understand key context such as the UI level and network request status when the crash occurs, helps reproduce problems during operation and maintenance, and accelerates problem location.

[0072] In summary, this embodiment constructs an application-level protection layer through dynamic method interception and exchange, truly realizing systematic, non-invasive, user-imperceptible and information-traceable protection, significantly reducing the App crash rate while ensuring that developers can accurately locate the cause of the crash, forming a complete abnormal monitoring-protection-reporting closed-loop process. Specifically, on the one hand, the traditional solution is relatively passive, and protection code needs to be manually added for each crash point. Even the protection systems currently available on the market that use the monitoring mechanism designed with security judgment are mostly limited to the development stage (static code inspection), message forwarding stage or single-point protection at runtime. This processing method is mostly preventive, and security judgments are made when using it. However, a large amount of data is returned by the background interface. During the use process, many data values ​​are directly taken and used without making security judgments or are not within the scope of security judgments. It is still difficult to avoid the problem of App abnormal crashes, and there is a risk of omissions. For this reason, this embodiment adds protection methods to the system class through classification design without modifying the original class code, and cooperates with the Runtime full-link method interception system to execute protection method exchanges locally without modifying the original code. It can intercept exceptions and dynamically repair execution logic in real time at the moment of a crash. The application continues to run after the crash is intercepted, realizing global dynamic protection without modifying the source code, covering all code paths, and achieving an organic combination of static protection and dynamic protection. It not only overcomes the protection points missed in the development stage, but also avoids the invasion of the code structure by traditional Try-Catch, so that users can keep the APP responsive when encountering a crash scenario and complete the exception repair without perception. Moreover, unlike the performance loss that may be introduced by existing code rewriting, this embodiment uses the Runtime-based interception mechanism to ensure that the normal process executes the original method without additional overhead. It only triggers the interception and exchange protection logic in the event of an exception, with extremely low resource usage. It is based on the standardized implementation of Runtime and is compatible with all iOS versions. There is no need to adapt to system upgrades, no private API is involved, and it complies with the App Store review specifications to ensure compliance (for example, hot repairs are prohibited by Apple).

[0073] On the other hand, traditional log reporting relies on callbacks after a crash occurs, resulting in incomplete information and inability to associate with protection scenarios. Traditional crash logs also have technical problems such as reliance on symbol table parsing, collection lags, and inability to locate context. This embodiment intercepts and exchanges system-like methods that are prone to crashes through the entire Runtime chain, allowing the protection method to take over the execution process at the moment the crash occurs, thereby creating an execution opportunity for log collection. It is understandable that if the crash process is not intercepted by Runtime, log collection will not be able to execute due to process termination. Only when the crash is intercepted can crash log collection be completed in the same execution process, making the integrity of log records possible. Therefore, this embodiment can embed log collection logic in the protection logic to ensure that crash information is completely preserved and realize real-time reporting of structured crash logs triggered by protection. Crash protection and log reporting form a closed loop to fill the gap between protection blind spots in the development stage and protection capabilities during online runtime, avoiding information loss caused by process termination in traditional crash capture solutions, and enabling developers to accurately locate the root cause of the problem through real-time reported crash logs, achieving the technical effect of "1+1>2".

[0074] Example 2:

[0075] This embodiment only compares Figure 1 The differences between the first embodiment and the second embodiment are described below. The technical concepts of the remaining designs are similar to those of the first embodiment and will not be described in detail in this embodiment.

[0076] In this embodiment, crash scenarios include unrecognized selector, container out of bounds, KVO Crash, NSTimer circular reference, NSNull value processing, and non-main thread UI operations.

[0077] In this regard, in this embodiment, the implementation method of defining the corresponding system class protection method in each category is as follows:

[0078] 1. Unrecognized Selector (unimplemented method call): intercepts the original methods of "methodSignatureForSelector:" (the core method for generating method signatures) and "forwardInvocation:" (the final step for executing unrecognized methods), dynamically generates method signatures and forwards the call to avoid crashes.

[0079] Specifically, in this embodiment, if the crash scenario corresponding to the classification is an unrecognized selector, a protection method corresponding to the system class is defined in the classification, including:

[0080] Use the Runtime mechanism to swap the original method ("methodSignatureForSelector:" and "forwardInvocation:") with the predefined guard method ("safe_methodSignatureForSelector:" and "safe_forwardInvocation:");

[0081] When an object receives an unimplemented method call, the original method of the system class sequentially executes the message query (checks the class method list, calls it directly if found, and enters the next stage of dynamic resolution if the method is not found), dynamic resolution (developers can temporarily add methods by calling the instance method "resolveInstanceMethod" or the class method "resolveClassMethod"), and alternative receiver lookup (determines whether there are other objects that can handle the method, uses "forwardingTargetForSelector" to specify a new object for processing, and if there is no new object to process, enters the protection layer intervention step). If none of the three processes are processed, the protection layer intervention step is executed:

[0082] Intercept the original methods of "methodSignatureForSelector:" (the core method for generating method signatures) and "forwardInvocation:" (the final step for executing unrecognized methods);

[0083] Use [self respondsToSelector:aSelector] to determine whether the object has a corresponding method implementation. If so, return the original method signature (NSMethodSignature object containing metadata such as parameter types and return value type). If not, construct a method signature with a void return value and return it.

[0084] Generate an NSInvocation instance based on the method signature to encapsulate the method call information, and process it in the last step of message forwarding (that is, in the "safe_forwardInvocation:" after the exchange, check whether the method is an unimplemented method).

[0085] It is understandable that this protection solution intercepts unimplemented method calls during the message forwarding phase, and by dynamically generating legal signatures, forces the system to direct unrecognized method calls to the last step of message forwarding for processing, rather than crashing directly. It also implements security downgrade (such as silent processing or returning to default values) by manipulating the call details through the NSInvocation object.

[0086] 2. Container out of bounds (array, dictionary, etc.): Intercept the initialization and access methods (such as objectAtIndex:) of the exchange container class (such as NSArray), and use the addition, deletion, modification and query methods to perform protection operations, such as returning a null value or default value when out of bounds.

[0087] 3. KVO Crash (Observer Removal Error): Intercept and exchange the "removeObserver:forKeyPath:" method to perform safety protection operations to prevent crashes caused by repeated removal or invalid KeyPath.

[0088] 4. NSTimer circular reference: Use abstract proxy classes (such as KJProxyProtector) to weakly reference Target and break the strong reference cycle between NSTimer and Target.

[0089] Furthermore, in this embodiment, if the crash scenario corresponding to the category is NSTimer circular reference, a protection method for the corresponding system class is defined in the category, including:

[0090] Create a timer entry method (scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:);

[0091] When starting the app, intercept all timer instantiation requests and swap the created timer entry method;

[0092] Define the abstract intermediate class KJProxyProtector (core bridging role);

[0093] In the swapped method, the NSTimer instance strongly references KJProxyProtector (in compliance with the system API's holding rules), and KJProxyProtector only weakly references the native target, thus avoiding the formation of a circular reference loop of NSTimer → target → NSTimer.

[0094] Among them, when the timer is triggered, the system sends the method call corresponding to the selector to KJProxyProtector, and the proxy class forwards the message to weakTarget (if it has not been released) through objc_msgSend. If weakTarget has been released (weakTarget == nil), the proxy automatically terminates the message delivery to prevent invalid calls.

[0095] It is understandable that in the native process, NSTimer strongly references target. If target also strongly references NSTimer, neither can release the reference, resulting in a memory leak. To this end, this embodiment restructures NSTimer's object reference relationship and message passing link, making the relationship between target and NSTimer a weak reference. This means that target can be freely released, solving the circular reference problem.

[0096] Through the protection method provided in this embodiment, the strong reference between NSTimer and the business object is decoupled, and memory safety is achieved while retaining the timer function, completely eliminating the risk of memory leaks and crashes caused by circular references.

[0097] 5. NSNull value handling: intercepts and exchanges "methodSignatureForSelector:" and "forwardInvocation:" to return a safe response to method calls on NSNull objects.

[0098] 6. Non-main thread UI operation: Insert dispatch_async (main queue) in the swap method to force thread switching. Through [NSThread isMainThread] judgment, the UI operation is automatically switched to the main queue to solve the crash caused by the UI not being updated in the main thread.

[0099] Furthermore, in this embodiment, if the crash scenario corresponding to the classification is a non-main thread UI operation, a protection method for the corresponding system class is defined in the classification, including:

[0100] When the app is started, the core layout methods of UIView are intercepted and exchanged. The core layout methods of UIView include setNeedsLayout (marking that layout needs to be re-laid out), layoutIfNeeded (triggering layout immediately), layoutSubviews (subview layout implementation), and setNeedsUpdateConstraints (marking that constraints need to be updated);

[0101] In the exchanged method, [NSThread isMainThread] (Boolean judgment interface) is used to detect whether the current thread is the main thread (that is, the only thread in iOS that allows UI operations). If a non-main thread call is detected, the interception is triggered, and the UI operation code block is asynchronously dispatched to the main thread queue for execution. The thread scheduling mechanism of GCD (Grand Central Dispatch) is used to ensure that subsequent operations are executed in the correct thread. If it is detected that the current thread is already the main thread, the original method implementation (the original function pointed to by the IMP pointer) is called directly to ensure that the system's original UI processing flow is not interfered with.

[0102] This embodiment combines dynamic interception with thread scheduling to build a transparent UI thread safety protection layer at the Runtime layer, effectively preventing crashes caused by multi-threaded misoperation.

[0103] In summary, this embodiment solves the core problems of existing technologies, such as isolated protection measures and poor crash protection effects, by uniformly handling multiple crash scenarios. Specifically:

[0104] 1. Unified interception framework: This embodiment builds a central interception layer within the system classes (NSObject / NSArray / UIView, etc.) based on the Objective-C Runtime's dynamic method swizzling technology. This layer integrates previously dispersed crash prevention logic (such as method signature processing, thread checking, and circular reference decoupling) into a unified message processing pipeline. By sharing the method swizzling initialization module, log reporting interface, and thread safety lock, it avoids duplicate code generation and significantly reduces memory usage.

[0105] 2. Dynamic Resource Management: This system reconstructs reference relationship topology through abstract intermediate classes (such as KJProxyProtector), establishes a "protection proxy bridge" in strong reference scenarios such as NSTimer, and combines weak reference chains (Weak Target) with message redirection (objc_msgSend) to provide two-way protection for memory leak and crash prevention, reducing the incidence of display memory exceptions.

[0106] 3. Thread safety enhancement: In the protection of non-main thread UI operations, a double insurance strategy of dispatch_async asynchronous dispatch and [NSThread isMainThread] atomic judgment is adopted. Through GCD queue priority control (QoS Class), it ensures that UI operations comply with thread safety rules, avoid main thread blocking, and reduce the fluctuation of interface rendering frame rate.

[0107] Example 3:

[0108] Another embodiment of this specification provides a computer-readable storage medium storing instructions that, when executed on a computer or processor, cause the computer or processor to perform one or more steps of a method for preventing iOS crashes in the aforementioned embodiment. If the components of the aforementioned electronic device are implemented as software functional units and used as independent downstream task predictions or tasks, they can be stored in the computer-readable storage medium.

[0109] In the above embodiments, it can be implemented in whole or in part by software, hardware, firmware or any combination thereof. When software is used for implementation, it can be implemented in whole or in part in the form of a computer program product. The computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, the process or function according to the embodiment of this specification is generated in whole or in part. The computer can be a general-purpose computer, a special-purpose computer, a computer network, or other programmable devices. The computer instructions can be stored in a computer-readable storage medium or transmitted via a computer-readable storage medium. The computer instructions can be transmitted from a website, computer, server or data center to another website, computer, server or data center via a wired (e.g., coaxial cable, optical fiber, digital subscriber line (DSL)) or wireless (e.g., infrared, wireless, microwave, etc.) mode. The computer-readable storage medium can be any available medium that a computer can access or a data storage device such as a server or data center that includes one or more available media integrations. Available media may be magnetic media (eg, floppy disks, hard disks, magnetic tapes), optical media (eg, digital versatile discs (DVDs)), or semiconductor media (eg, solid state disks (SSDs)).

[0110] The above description is merely an illustration of the preferred embodiments disclosed in this application and the technical principles employed. Those skilled in the art should understand that the scope of protection provided by this disclosure is not limited to the technical solutions formed by the specific combination of the above-mentioned technical features, but also encompasses other technical solutions formed by any combination of the above-mentioned technical features or their equivalents without departing from the above-mentioned disclosed concepts. For example, a technical solution formed by replacing the above-mentioned features with (but not limited to) technical features with similar functions disclosed in this disclosure.

[0111] In addition, although each operation is described in a specific order, this should not be understood as requiring these operations to be performed in the specific order shown or in a sequential order. Under certain circumstances, multitasking and parallel processing may be advantageous. Similarly, although some specific implementation details have been included in the above discussion, these should not be interpreted as limiting the scope of the present disclosure. Some features described in the context of a separate embodiment can also be implemented in a single embodiment in combination. On the contrary, the various features described in the context of a single embodiment can also be implemented in multiple embodiments individually or in any suitable sub-combination mode.

Claims

1. A method for preventing iOS from crashing abnormally, characterized in that: The following steps are involved: Design independent protection logic for different types of crash scenarios and package them into a protection SDK; Embed the protection SDK into the App to run the protection SDK when the App is launched; When running the protection SDK, the runtime mechanism is used to intercept and exchange system class methods to achieve real-time protection at the application layer, and the App continues to run after the exchange; Complete crash log collection and report crash log information in the same execution process of interception.

2. The iOS abnormal crash protection method according to claim 1, characterized in that: Design independent protection logic for different types of crash scenarios, including: For crash scenarios that require protection, create categories for corresponding system classes and define protection methods for the corresponding system classes in each category.

3. The iOS abnormal crash protection method according to claim 2, wherein: The Runtime mechanism is used to directly intercept and exchange system class methods to achieve real-time protection at the application layer, including: Use the Runtime mechanism to obtain the original methods and protection methods of system classes; Intercept the system class methods corresponding to each category, and use Method Swizzling to swap the original method of the system class with the protection method to achieve crash and flash back protection.

4. The iOS abnormal crash protection method according to claim 3, wherein: Swap the original methods of system classes with guard methods, including: The original method of the system class is exchanged with the guard method, and the dispatch_once thread safety mechanism is implemented to ensure that the exchange operation is performed only once.

5. The iOS abnormal crash protection method according to claim 2, wherein: The crash scenarios include unrecognized selectors, container out-of-bounds, KVO crashes, NSTimer circular references, NSNull value processing, and non-main-thread UI operations.

6. The iOS abnormal crash protection method according to claim 5, characterized in that: If the crash scenario corresponding to the classification is an unrecognized selector, a protection method for the corresponding system class is defined in the classification. This includes: when an object receives an unimplemented method call, the original method of the system class executes the message query, dynamic parsing, and backup receiver search processes in sequence. If none of the three processes are handled, the following steps are executed: Determine whether the object has a corresponding method implementation. If so, return the original method signature. If not, construct a method signature with a void return value and return it. Generate an NSInvocation instance based on the method signature to encapsulate the method call information and enter the final step of message forwarding for processing.

7. The iOS abnormal crash protection method according to claim 5, characterized in that: If the crash scenario corresponding to the category is NSTimer circular reference, define the corresponding system class protection method in the category, including: Create a timer entry method; When starting the app, intercept all timer instantiation requests and swap the created timer entry method; Define the abstract intermediate class KJProxyProtector; In the swapped methods, the NSTimer instance has a strong reference to the KJProxyProtector, which in turn has a weak reference to the native target.

8. The iOS abnormal crash protection method according to claim 5, characterized in that: If the crash scenario corresponding to the category is a non-main-thread UI operation, define the corresponding system class protection method in the category, including: When starting the app, the core layout methods of UIView are intercepted and exchanged. The core layout methods of UIView include setNeedsLayout, layoutIfNeeded, layoutSubviews, and setNeedsUpdateConstraints. In the swapped method, it is detected whether the current thread is the main thread. If a non-main thread call is detected, the interception is triggered and the UI operation code block is asynchronously dispatched to the main thread queue for execution. If it is detected that the current thread is already the main thread, the original method is directly called.

9. The iOS abnormal crash protection method according to claim 1, wherein: The crash log information includes the interception occurrence timestamp, crash scenario type, device information, crash stack information and business context. The reported crash log information includes: Transfer crash log information from the protection SDK to the main App program; The main app program uploads the crash log information to a cloud server or a third-party platform.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the method for preventing iOS from abnormal crashes according to any one of claims 1 to 9 is implemented.