解决delegate已经释放引起的crash的关健点在于delegate的isa指针是否有变化。下面是测试工程的代码:
//
// ViewController.h
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UIAView.h"
@interface ViewController : UIViewController
{
UIAView* aView;
}
@end
//
// ViewController.m
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "ViewController.h"
#import "UIAView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
aView = [[UIAView alloc]initWithFrame:CGRectMake(0, 0,200, 100)];
[self.view addSubview:aView];
[aView release];
}
@end
//
// UIAView.h
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UIBObject.h"
@interface UIAView : UIView <UIAViewDelegate>
{
UIBObject* obj;
}
-(void) test;
-(void) removeView;
@end
//
// UIAView.m
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "UIAView.h"
@implementation UIAView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
obj = [[UIBObject alloc]init];
obj.delegate = self;
[self performSelector:@selector(removeView) withObject:nil afterDelay:10];
}
return self;
}
-(void) removeView
{
[self removeFromSuperview];
}
-(void) test
{
}
- (void)dealloc
{
if(obj)
{
[obj release];
}
[super dealloc];
}
@end
//
// UIBObject.h
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol UIAViewDelegate
-(void)test;
@end
@interface UIBObject : NSObject
{
id <UIAViewDelegate> delegate;
int classIsa;
}
@property (nonatomic, assign) id <UIAViewDelegate> delegate;
-(void) callDelegate;
@end
//
// UIBObject.m
// testDelegate
//
// Created by Qingrong Zeng on 12-5-25.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "UIBObject.h"
@implementation UIBObject
@synthesize delegate;
-(id) init
{
if (self = [super init])
{
[self performSelector:@selector(callDelegate) withObject:self afterDelay:30];
}
return self;
}
- (void)setDelegate:(id<UIAViewDelegate>)iDelegate
{
delegate = iDelegate;
NSString *delegateDescription = [[iDelegate class] description];
classIsa = (int)objc_getClass([delegateDescription UTF8String]);
}
-(void) callDelegate
{
if((int)delegate->isa != classIsa)
{
return;
}
[delegate test];
}
@end
转载于:https://blog.51cto.com/realwizard/912919