ios开发中init()方法重复执行,以及实例变量错乱的灵异现象

刚才发现一个灵异现象,还没找到原因,先记录一下:

我的MainViewController里有2个辅助类的引用:

@implementation YLSMainViewController

YLSLogoutDelegate *logoutDelegate;
YLSBackupDelegate *backupDelegate;
YLSResumeDelegate *resumeDelegate;

然后在viewDidLoad里创建这2个类的实例:

backupDelegate = [YLSBackupDelegate new];
resumeDelegate = [YLSResumeDelegate new];

下面分别是2个类的init()方法:

- (id)init
{
    if(self = [super init]){
        tasks = [NSMutableArray new];
        
        // 备份任务在下面依次添加
        [tasks addObject:[YLSMemberBackupTask new]];
        [tasks addObject:[YLSEmployeeBackupTask new]];
        [tasks addObject:[YLSServiceBackupTask new]];
        [tasks addObject:[YLSShowBackupTask new]];
        [tasks addObject:[YLSBillBackupTask new]];
        [tasks addObject:[YLSUserBackupTask new]];
        [tasks addObject:[YLSEnterpriseBackupTask new]];
    }
    return self;
}

- (id)init
{
    if(self = [super init]){
        tasks = [NSMutableArray new];
        
        // 恢复任务在下面依次添加
        [tasks addObject:[YLSEmployeeResumeTask new]];
    }
    return self;
}

结果运行的时候报异常,应用崩溃:

2013-12-17 16:40:42.306 NailShop[13926:456b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[YLSEmployeeResumeTask doBackup:]: unrecognized selector sent to instance 0xecb8990'


从异常信息看到,BackupDelegate的实例变量tasks里,存放的居然是ResumeDelegate的同名实例变量tasks里的对象……然后DEBUG又发现一个问题,BackupDelegate的init()方法执行了2遍,ResumeDelegate是正常的只执行一遍

反复检查没发现什么问题,最后只好把ResumeDelegate里的那个NSMutableArray的变量名改成resumeTasks,避免重名

问题是解决了,但是实在太灵异了……有人知道这个问题的原因吗?

你可能感兴趣的:(移动开发)