iOS Delegate使用assign修饰崩溃(应使用weak

2022-05-24  本文已影响0人  心猿意码_
问题描述:

Delegate使用assign修饰是产生崩溃。

原因:
为什么用weak不用assign
示例代码如下:

Book文件

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
@protocol TestlDelegate <NSObject>

@optional

-(void)testDelegate:(NSString *)str;

@end

@interface Book : NSObject
@property (nonatomic,assign) id <TestlDelegate> delegate;

-(void)test;
@end

NS_ASSUME_NONNULL_END

#import "Book.h"

@implementation Book
-(void)test{
    if(self.delegate && [self.delegate respondsToSelector:@selector(testDelegate:)]){
        [self.delegate testDelegate:@"我是一条测试回调"];
    }
}
@end

Store文件

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Store : NSObject

@end

NS_ASSUME_NONNULL_END

#import "Store.h"

@interface Store ()

@end

@implementation Store

@end

ViewController中调用


#import "ViewController.h"
#import "Book.h"
#import "Store.h"

@interface ViewController ()<TestlDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
    Book *book = [[Book alloc] init];
    
    {    //从作用域出去后store就会释放,此时delegate并未释放或置为nil,成为了一个野指针,所以再调用 [book test]; 时崩溃
        Store *store = [[Store alloc] init];
        book.delegate = store;
    }
    
    [book test];
}

@end

总结:store从作用域出去后,store就会释放,此时delegate并未释放或置为nil,成为了一个野指针,所以再调用 [book test];时崩溃,将assign改为weak则可解决此崩溃问题。

上一篇 下一篇

猜你喜欢

热点阅读