Xcode 15跑工程崩溃/报错记录

2,867 阅读1分钟

1. Swift class extensions and categories on Swift classes are not allowed to have +load methods崩溃(Xcode15版本相关,iOS版本无关)

iOS不允许swift类实现+load方法,即使是oc实现的extensions和categories也不行。举例:

MyContentViewController.swift中定义了一个MyContentViewController类 iOS不允许swift类实现+load方法,即使是oc实现的extensions和categories也不行。举例:

@objcMembers
public class MyContentViewController: UIViewController {
    public override func viewDidLoad() {
        super.viewDidLoad()
    }
}

然后用OC给MyContentViewController添加了一个分类,在分类中实现了+load方法:

#import "MyContentViewController+ext.h"

@implementation MyContentViewController (ext)

+ (void)load {
    NSLog(@"MyContentViewController load");
}

@end

在程序启动的时候就直接崩溃了。

解决方案(仅供参考):

  1. 一些需要前置的操作,可以放到didFinishLaunchingWithOptions方法中统一处理
  2. 在oc的load方法里面统一处理swift需要在load方法中完成的任务
  3. 必须用load方法的话,直接使用OC类,不要通过上面示例的方式。

2. ’UIGraphicsBeginImageContext() failed to allocate CGBitampContext: size={0, 0}, scale=3.000000, bitmapInfo=0x2002. Use UIGraphicsImageRenderer to avoid this assert.'进了断言(iOS17+Xcode15才会崩溃) 点进UIGraphicsBeginImageContextWithOptions中看,这个已经被废弃了,需要使用UIGraphicsImageRenderer进行替换。

image.png

解决方案(仅供参考):

  1. 确保UIGraphicsBeginImageContextWithOptions和UIGraphicsBeginImageContext中传入size的长和宽不能为0。
  2. 使用UIGraphicsImageRenderer进行替换处理,如:

原先实现:

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
	UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  	CGContextRef context = UIGraphicsGetCurrentContext();
  	CGContextSetFillColorWithColor(context, color.CGColor);
  	CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
  	UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  	UIGraphicsEndImageContext();
  	return newImage;
}

改之后:

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.opaque = NO;
    format.scale = [UIScreen mainScreen].scale;
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:format];
    UIImage *newImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
    }];
    return newImage;
}