首页 > 其他分享 >iOS开发基础133-崩溃预防

iOS开发基础133-崩溃预防

时间:2024-07-18 17:32:20浏览次数:14  
标签:observer void safe iOS selector 133 class 崩溃 self

现代移动应用的用户体验依赖于其稳定性和可靠性。然而,在开发过程中,我们时常会遇到各种崩溃问题。崩溃不仅会影响用户的使用体验,还可能损害应用的声誉。因此,本文将详细介绍一个名为CrashPrevention的工具类,它能够为iOS开发者提供多方面的崩溃预防措施,借助该工具类,开发者能够有效减少崩溃的发生,并提升应用的稳定性。

CrashPrevention工具类概述

CrashPrevention是一个易于集成的工具类,专为iOS应用中的多种常见崩溃情况提供预防措施。通过调用相关方法,开发者可以开启针对数组操作、字典操作、未识别的选择器、通知中心、键值观察(KVO)、字符串操作、多线程操作以及UI线程操作的保护机制。特别值得一提的是,CrashPrevention让开发者可以通过一个全局的 isDebug 标志,灵活控制是否启用这些崩溃预防措施。

CrashPrevention.h 头文件

首先,我们来看一下CrashPrevention的头文件,其中定义了所有的预防方法:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CrashPrevention : NSObject

// 设置是否在 Debug 模式中启用崩溃预防
+ (void)setDebugMode:(BOOL)isDebug;

// 启用所有崩溃保护
+ (void)enableAllCrashPrevention;

// 启用各类崩溃保护
+ (void)enableArrayProtection;
+ (void)enableDictionaryProtection;
+ (void)enableSelectorProtection;
+ (void)enableNotificationProtection;
+ (void)enableKVOCrashProtection;
+ (void)enableStringProtection;
+ (void)enableThreadSafetyProtection;
+ (void)enableUIThreadProtection;

@end

CrashPrevention.m 实现文件

接下来,我们深入了解实现文件的设计思路和具体代码。

全局Debug标志

@implementation CrashPrevention

// 用于记录是否在 Debug 模式下启用崩溃预防
static BOOL debugModeEnabled = NO;

// 设置是否在 Debug 模式中启用崩溃预防
+ (void)setDebugMode:(BOOL)isDebug {
    debugModeEnabled = isDebug;
}

通过 static BOOL debugModeEnabled,我们可以记录是否启用调试模式,基于此标志决定是否启用崩溃预防功能。

启用所有崩溃保护

+ (void)enableAllCrashPrevention {
    if (!debugModeEnabled) {
        return;
    }
    [self enableArrayProtection];
    [self enableDictionaryProtection];
    [self enableSelectorProtection];
    [self enableNotificationProtection];
    [self enableKVOCrashProtection];
    [self enableStringProtection];
    [self enableThreadSafetyProtection];
    [self enableUIThreadProtection];
}

该方法通过检查 debugModeEnabled 标志,决定是否依次启用各类崩溃保护。

数组越界保护

+ (void)enableArrayProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayI")
                           original:@selector(objectAtIndex:)
                           swizzled:@selector(safe_objectAtIndex:)];
        [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM")
                           original:@selector(objectAtIndex:)
                           swizzled:@selector(safe_objectAtIndex:)];
    });
}

- (id)safe_objectAtIndex:(NSUInteger)index {
    if (index < self.count) {
        return [self safe_objectAtIndex:index];
    } else {
        @try {
            NSLog(@"Array index out of bound: %lu", (unsigned long)index);
        } @catch (NSException *exception) {
            // 处理异常
        }
        return nil;
    }
}

通过 Method Swizzling,我们可以将数组的 objectAtIndex: 方法替换为安全版本。在越界的情况下,返回 nil 并记录日志,而不会崩溃。

字典键值检查保护

+ (void)enableDictionaryProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSDictionaryI")
                           original:@selector(objectForKey:)
                           swizzled:@selector(safe_objectForKey:)];
    });
}

- (id)safe_objectForKey:(id)key {
    if (key) {
        return [self safe_objectForKey:key];
    } else {
        @try {
            NSLog(@"Attempted to access dictionary with nil key");
        } @catch (NSException *exception) {
            // 处理异常
        }
        return nil;
    }
}

类似地,通过 Method Swizzling,我们可以将 objectForKey: 方法替换为安全版本,防止使用 nil 作为键值时的崩溃。

消息转发保护

+ (void)enableSelectorProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method forwardMethod = class_getInstanceMethod([self class], @selector(forwardingMethod:));
        class_addMethod([self class], NSSelectorFromString(@"unrecognizedSelectorHandler"), method_getImplementation(forwardMethod), method_getTypeEncoding(forwardMethod));
    });
}

- (void)forwardingMethod:(SEL)aSelector {}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (!debugModeEnabled) {
        return [super resolveInstanceMethod:sel];
    }
    class_addMethod([self class], sel, class_getMethodImplementation([self class], @selector(forwardingMethod:)), "v@:");
    return YES;
}

通过添加一个默认的 forwardingMethod: ,我们防止调用未实现的方法时崩溃。

通知中心保护

+ (void)enableNotificationProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[NSNotificationCenter class]
                           original:@selector(addObserver:selector:name:object:)
                           swizzled:@selector(safe_addObserver:selector:name:object:)];
        [self swizzleInstanceMethod:[NSNotificationCenter class]
                           original:@selector(removeObserver:name:object:)
                           swizzled:@selector(safe_removeObserver:name:object:)];
    });
}

- (void)safe_addObserver:(NSObject *)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject {
    if (observer) {
        [[NSNotificationCenter defaultCenter] safe_addObserver:observer selector:aSelector name:aName object:anObject];
    } else {
        @try {
            NSLog(@"Attempted to add a nil observer for name: %@", aName);
        } @catch (NSException *exception) {
            // 处理异常
        }
    }
}

- (void)safe_removeObserver:(NSObject *)observer name:(NSString *)aName object:(id)anObject {
    if (observer) {
        [[NSNotificationCenter defaultCenter] safe_removeObserver:observer name:aName object:anObject];
    } else {
        @try {
            NSLog(@"Attempted to remove a nil observer for name: %@", aName);
        } @catch (NSException *exception) {
            // 处理异常
        }
    }
}

在添加和移除观察者时进行空检查,防止空观察者导致的崩溃。

KVO 保护

+ (void)enableKVOCrashProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[NSObject class]
                           original:@selector(addObserver:forKeyPath:options:context:)
                           swizzled:@selector(safe_addObserver:forKeyPath:options:context:)];
        [self swizzleInstanceMethod:[NSObject class]
                           original:@selector(removeObserver:forKeyPath:)
                           swizzled:@selector(safe_removeObserver:forKeyPath:)];
    });
}

- (void)safe_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
    if (observer && keyPath) {
        [self safe_addObserver:observer forKeyPath:keyPath options:options context:context];
    } else {
        @try {
            NSLog(@"Attempted to add observer with nil observer or key path: %@", keyPath);
        } @catch (NSException *exception) {
            // 处理异常
        }
    }
}

- (void)safe_removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath {
    if (observer && keyPath) {
        [self safe_removeObserver:observer forKeyPath:keyPath];
    } else {
        @try {
            NSLog(@"Attempted to remove observer with nil observer or key path: %@", keyPath);
        } @catch (NSException *exception) {
            // 处理异常
        }
    }
}

在添加和移除KVO时进行必要检查,确保参数合法,防止崩溃。

字符串越界检查

+ (void)enableStringProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSCFConstantString")
                           original:@selector(substringFromIndex:)
                           swizzled:@selector(safe_substringFromIndex:)];
    });
}

- (NSString *)safe_substringFromIndex:(NSUInteger)from {
    if (from <= self.length) {
        return [self safe_substringFromIndex:from];
    } else {
        @try {
            NSLog(@"String index out of bound: %lu", (unsigned long)from);
        } @catch (NSException *exception) {
            // 处理异常
        }
        return nil;
    }
}

通过交换NSString的相关方法,确保在越界访问时返回 nil 并记录日志,从而避免崩溃。

线程安全保护

+ (void)enableThreadSafetyProtection {
    if (!debugModeEnabled) {
        return;
    }
    // 实现是与具体使用场景相关的,需要结合项目实际情况实现
}

这部分的实现高度依赖于具体的使用场景,比如可以使用 dispatch_barrier_asyncNSLock 等技术实现。

UI线程保护

+ (void)enableUIThreadProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[UIView class]
                           original:@selector(setNeedsLayout)
                           swizzled:@selector(safe_setNeedsLayout)];
    });
}

- (void)safe_setNeedsLayout {
    if ([NSThread isMainThread]) {
        [self safe_setNeedsLayout];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self safe_setNeedsLayout];
        });
        @try {
            NSLog(@"setNeedsLayout was called off the main thread. Fixed by dispatching to main queue.");
        } @catch (NSException *exception) {
            // 处理异常
        }
    }
}

确保UI操作总在主线程进行,如果不是,则调度到主线程执行,并记录警告日志。

方法交换

#pragma mark - Method Swizzling
+ (void)swizzleInstanceMethod:(Class)cls original:(SEL)originalSelector swizzled:(SEL)swizzledSelector {
    Method originalMethod = class_getInstanceMethod(cls, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);

    BOOL didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
@end

核心方法交换逻辑,通过 Method Swizzling 替换原有的方法实现。

使用CrashPrevention工具类

在应用启动时初始化CrashPrevention,并设置是否启用调试模式:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 设置 Debug 模式
    #ifdef DEBUG
        [CrashPrevention setDebugMode:YES];
    #else
        [CrashPrevention setDebugMode:NO];
    #endif
    
    [CrashPrevention enableAllCrashPrevention];
    return YES;
}

总结

CrashPrevention工具类为iOS开发者提供了多个方面的崩溃预防措施,通过简单调用,即可为数组、字典、未识别选择器、通知中心、KVO、字符串、多线程和UI线程的操作提供全面的保护。特别是通过 isDebug 标志,让开发者可以灵活控制这些预防措施在调试阶段和正式发布中的启用状态。借助这一工具类,开发者能够有效减少崩溃问题的发生,提升应用的稳定性和用户体验。

最后附上完整代码:

CrashPrevention.h文件

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CrashPrevention : NSObject

// 设置是否在 Debug 模式中启用崩溃预防
+ (void)setDebugMode:(BOOL)isDebug;

// 启用所有崩溃保护
+ (void)enableAllCrashPrevention;

// 启用各类崩溃保护
+ (void)enableArrayProtection;
+ (void)enableDictionaryProtection;
+ (void)enableSelectorProtection;
+ (void)enableNotificationProtection;
+ (void)enableKVOCrashProtection;
+ (void)enableStringProtection;
+ (void)enableThreadSafetyProtection;
+ (void)enableUIThreadProtection;

@end

CrashPrevention.m文件

#import "CrashPrevention.h"
#import <objc/runtime.h>

@implementation CrashPrevention

// 用于记录是否在 Debug 模式下启用崩溃预防
static BOOL debugModeEnabled = NO;

// 设置是否在 Debug 模式中启用崩溃预防
+ (void)setDebugMode:(BOOL)isDebug {
    debugModeEnabled = isDebug;
}

// 启用所有崩溃保护
+ (void)enableAllCrashPrevention {
    if (!debugModeEnabled) {
        return;
    }
    [self enableArrayProtection];
    [self enableDictionaryProtection];
    [self enableSelectorProtection];
    [self enableNotificationProtection];
    [self enableKVOCrashProtection];
    [self enableStringProtection];
    [self enableThreadSafetyProtection];
    [self enableUIThreadProtection];
}

#pragma mark - Array Protection
+ (void)enableArrayProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayI")
                           original:@selector(objectAtIndex:)
                           swizzled:@selector(safe_objectAtIndex:)];
        [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM")
                           original:@selector(objectAtIndex:)
                           swizzled:@selector(safe_objectAtIndex:)];
    });
}

- (id)safe_objectAtIndex:(NSUInteger)index {
    if (index < self.count) {
        return [self safe_objectAtIndex:index];
    } else {
        @try {
            NSLog(@"Array index out of bound: %lu", (unsigned long)index);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            return nil;
        }
    }
}

#pragma mark - Dictionary Protection
+ (void)enableDictionaryProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSDictionaryI")
                           original:@selector(objectForKey:)
                           swizzled:@selector(safe_objectForKey:)];
        [self swizzleInstanceMethod:NSClassFromString(@"__NSDictionaryM")
                           original:@selector(objectForKey:)
                           swizzled:@selector(safe_objectForKey:)];
    });
}

- (id)safe_objectForKey:(id)key {
    if (key) {
        return [self safe_objectForKey:key];
    } else {
        @try {
            NSLog(@"Attempted to access dictionary with nil key");
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            return nil;
        }
    }
}

#pragma mark - Selector Protection
+ (void)enableSelectorProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method forwardMethod = class_getInstanceMethod([self class], @selector(forwardingMethod:));
        class_addMethod([self class], NSSelectorFromString(@"unrecognizedSelectorHandler"), method_getImplementation(forwardMethod), method_getTypeEncoding(forwardMethod));
    });
}

- (void)forwardingMethod:(SEL)aSelector {}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (!debugModeEnabled) {
        return [super resolveInstanceMethod:sel];
    }
    class_addMethod([self class], sel, class_getMethodImplementation([self class], @selector(forwardingMethod:)), "v@:");
    return YES;
}

#pragma mark - Notification Protection
+ (void)enableNotificationProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[NSNotificationCenter class]
                           original:@selector(addObserver:selector:name:object:)
                           swizzled:@selector(safe_addObserver:selector:name:object:)];
        [self swizzleInstanceMethod:[NSNotificationCenter class]
                           original:@selector(removeObserver:name:object:)
                           swizzled:@selector(safe_removeObserver:name:object:)];
        [self swizzleInstanceMethod:[NSNotificationCenter class]
                           original:@selector(removeObserver:)
                           swizzled:@selector(safe_removeObserver:)];
    });
}

- (void)safe_addObserver:(NSObject *)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject {
    if (observer) {
        [[NSNotificationCenter defaultCenter] safe_addObserver:observer selector:aSelector name:aName object:anObject];
    } else {
        @try {
            NSLog(@"Attempted to add a nil observer for name: %@", aName);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

- (void)safe_removeObserver:(NSObject *)observer {
    if (observer) {
        [[NSNotificationCenter defaultCenter] safe_removeObserver:observer];
    } else {
        @try {
            NSLog(@"Attempted to remove a nil observer");
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

- (void)safe_removeObserver:(NSObject *)observer name:(NSString *)aName object:(id)anObject {
    if (observer) {
        [[NSNotificationCenter defaultCenter] safe_removeObserver:observer name:aName object:anObject];
    } else {
        @try {
            NSLog(@"Attempted to remove a nil observer for name: %@", aName);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

#pragma mark - KVO Protection
+ (void)enableKVOCrashProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[NSObject class]
                           original:@selector(addObserver:forKeyPath:options:context:)
                           swizzled:@selector(safe_addObserver:forKeyPath:options:context:)];
        [self swizzleInstanceMethod:[NSObject class]
                           original:@selector(removeObserver:forKeyPath:)
                           swizzled:@selector(safe_removeObserver:forKeyPath:)];
    });
}

- (void)safe_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
    if (observer && keyPath) {
        [self safe_addObserver:observer forKeyPath:keyPath options:options context:context];
    } else {
        @try {
            NSLog(@"Attempted to add observer with nil observer or key path: %@", keyPath);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

- (void)safe_removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath {
    if (observer && keyPath) {
        [self safe_removeObserver:observer forKeyPath:keyPath];
    } else {
        @try {
            NSLog(@"Attempted to remove observer with nil observer or key path: %@", keyPath);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

#pragma mark - String Protection
+ (void)enableStringProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:NSClassFromString(@"__NSCFConstantString")
                           original:@selector(substringFromIndex:)
                           swizzled:@selector(safe_substringFromIndex:)];
        [self swizzleInstanceMethod:NSClassFromString(@"__NSCFConstantString")
                           original:@selector(substringToIndex:)
                           swizzled:@selector(safe_substringToIndex:)];
        [self swizzleInstanceMethod:NSClassFromString(@"__NSCFConstantString")
                           original:@selector(substringWithRange:)
                           swizzled:@selector(safe_substringWithRange:)];
    });
}

- (NSString *)safe_substringFromIndex:(NSUInteger)from {
    if (from <= self.length) {
        return [self safe_substringFromIndex:from];
    } else {
        @try {
            NSLog(@"String index out of bound: %lu", (unsigned long)from);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            return nil;
        }
    }
}

- (NSString *)safe_substringToIndex:(NSUInteger)to {
    if (to <= self.length) {
        return [self safe_substringToIndex:to];
    } else {
        @try {
            NSLog(@"String index out of bound: %lu", (unsigned long)to);
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            return nil;
        }
    }
}

- (NSString *)safe_substringWithRange:(NSRange)range {
    if (range.location + range.length <= self.length) {
        return [self safe_substringWithRange:range];
    } else {
        @try {
            NSLog(@"String range out of bound: %@", NSStringFromRange(range));
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            return nil;
        }
    }
}

#pragma mark - Thread Safety Protection
+ (void)enableThreadSafetyProtection {
    if (!debugModeEnabled) {
        return;
    }
    // 实现是与具体使用场景相关的,需要结合项目实际情况实现
}

#pragma mark - UI Thread Protection
+ (void)enableUIThreadProtection {
    if (!debugModeEnabled) {
        return;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceMethod:[UIView class]
                           original:@selector(setNeedsLayout)
                           swizzled:@selector(safe_setNeedsLayout)];
        [self swizzleInstanceMethod:[UIView class]
                           original:@selector(setNeedsDisplay)
                           swizzled:@selector(safe_setNeedsDisplay)];
        [self swizzleInstanceMethod:[UIView class]
                           original:@selector(setNeedsDisplayInRect:)
                           swizzled:@selector(safe_setNeedsDisplayInRect:)];
    });
}

- (void)safe_setNeedsLayout {
    if ([NSThread isMainThread]) {
        [self safe_setNeedsLayout];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self safe_setNeedsLayout];
        });
        @try {
            NSLog(@"setNeedsLayout was called off the main thread. Fixed by dispatching to main queue.");
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

- (void)safe_setNeedsDisplay {
    if ([NSThread isMainThread]) {
        [self safe_setNeedsDisplay];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self safe_setNeedsDisplay];
        });
        @try {
            NSLog(@"setNeedsDisplay was called off the main thread. Fixed by dispatching to main queue.");
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

- (void)safe_setNeedsDisplayInRect:(CGRect)rect {
    if ([NSThread isMainThread]) {
        [self safe_setNeedsDisplayInRect:rect];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self safe_setNeedsDisplayInRect:rect];
        });
        @try {
            NSLog(@"setNeedsDisplayInRect: was called off the main thread. Fixed by dispatching to main queue.");
        } @catch (NSException *exception) {
            // 处理异常
        } @finally {
            // 什么也不做
        }
    }
}

#pragma mark - Method Swizzling
+ (void)swizzleInstanceMethod:(Class)cls original:(SEL)originalSelector swizzled:(SEL)swizzledSelector {
    Method originalMethod = class_getInstanceMethod(cls, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);

    BOOL didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@end

标签:observer,void,safe,iOS,selector,133,class,崩溃,self
From: https://www.cnblogs.com/chglog/p/18310066

相关文章

  • 远程办公最重要的是稳定,ToDesk如何实现“0崩溃”
    随着数字化转型的加速,越来越多的企业开始采用远程办公模式。据统计,2023年全球远程办公企业和从业人员数量暴增,成为了一种不可逆转的趋势。然而,这种模式的普及也带来了新的问题,其中最令企业头疼的便是远程办公软件能否稳定顺畅的支持员工进行线上工作。传统的远程控制常常出现卡顿......
  • iOS开发基础132-POSIX线程库
    POSIX线程库,通常称为Pthreads(POSIXThreads),是一个基于POSIX标准的多线程编程接口。它为多线程应用程序提供了一组标准化的API,兼容多个UNIX系统,包括Linux、macOS等。POSIX线程库概览POSIX线程库主要包括以下几个组成部分:线程管理:创建和操作线程。线程同步:互斥锁(mut......
  • iOS开发基础131-isa指针
    iOS中isa指针是Objective-C对象内部的一个重要概念,它是实现对象与类之间关系的核心机制。深入理解isa指针对掌握Objective-C的底层运行机制和对象模型非常重要。1.什么是isa指针每个Objective-C对象都有一个isa指针,它指向这个对象所属的类。类本身也有一个isa指针,指向其元类(met......
  • iOS开发基础129-音频录制上传
    在Objective-C中,音频录制过程涉及几个关键步骤,包括配置录音设置、创建和启动录音机、处理录音会话以及将录制的音频文件上传到服务器。下面是一个详细的示例,包括创建一个简单的音频录制应用,以及将录制的音频文件上传到服务器的代码。1.设置音频会话我们需要使用AVFoundation框......
  • iOS开发基础127-深入探讨KVO
    一、基础KVO(Key-ValueObserving,键值观察)是Cocoa提供的一种机制,它允许我们观察属性的变化并做出响应。这种机制非常强大,广泛应用于各种编程场景,如数据绑定、状态变化监控等。在深入了解KVO之前,我们先从KVO的基本概念开始,然后逐步探讨其深层次应用和一些使用实践的注意事项......
  • 在 PowerShell 中Get-WmiObject Win32_PhysicalMemory,SMBIOSMemoryType 是一种用于描
    在PowerShell中Get-WmiObjectWin32_PhysicalMemory,SMBIOSMemoryType是一种用于描述系统中物理内存类型的属性。数字26表示特定的内存类型,具体为DDR4内存。每种内存类型在SMBIOS(SystemManagementBIOS)规范中都有一个对应的数字码,用来标识不同类型的内存。以下是一些常见......
  • iOS开发基础125-深入探索SDWebImage
    SDWebImage是一个流行的用于处理图像下载和缓存的库,广泛用于iOS开发中,提供了一系列方便的API来下载和缓存图像,以提高应用的性能和用户体验。以下是对其进行详细介绍和分析,包括其原理和底层实现。一、SDWebImage的主要功能图像下载和缓存:图像下载:使用异步方式从网络上下......
  • iOS开发基础124-RunLoop实现卡顿检测
    利用RunLoop实现卡顿检测的基本思路是通过监听RunLoop的状态变化来判断主线程的执行时长。如果RunLoop在某个状态停留的时间超过了预设的时间阈值,则认为发生了卡顿。在具体实现中,可以利用CFRunLoopObserver来监听RunLoop的状态变化,并记录时间差。一、卡顿检测的基本原......
  • iOS开发基础122-RunLoop
    深入探讨RunLoop的底层实现需要了解CoreFoundation框架中的CFRunLoop以及与RunLoop工作机制紧密相关的操作系统底层API。这些底层实现主要涉及到事件源、定时器和线程的调度机制。本文将深入剖析RunLoop的底层结构及其运行流程。一、RunLoop底层数据结构涉及RunLo......
  • iOS开发基础123-自动释放池
    自动释放池(AutoreleasePool)是Objective-C中用于管理内存的一个重要机制,它帮助开发者简化内存管理的工作。自动释放池的核心概念是将对象放入池中,在某个时刻由系统统一释放这些对象。这种机制在iOS和macOS的应用开发中广泛使用,尤其是在事件循环和线程运行时。为了深入理解其底层......