类之间相互引用--类A中需要调用类B中的方法,同时,类B中又要调用类A中的方法。(也被称为引用死锁,通常会出现编译错误)。
解决方法是,在类A中引用类B,并使类A成为类B的delegate,这样在类A中就可以调用类B中的方法,而在类B中可以设一个delegate属性,(这个delegate其实就是类A)就可以用[delegate msg]的方式来调用类A中的方法了。
具体实现如下:
** classA.h :
@interface ClassA<ClassBDelegate>
{
      ClassB *_B;
}
@property(retain)ClassB *B;
@end
** classA.m :
@implementation ClassA
@synthesize B = _B;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
      self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
      if (self) 
  {
            // Custom initialization
            self.B = [[ClassB alloc] init];
            [self.B setDelegate:self];
      }
      return self;
 
}
// ClassB delegate method
- (void)delegateMethod
{
     NSLog(@"This is a delegate Method !");
}
@end
** classB.h :
@protocol ClassBDelegate;
@interface ClassB
{
      id<ClassBDelegate>delegate;
}
@property(retain,nonatomic)id<ClassBDelegate>delegate;
@end
@protocol ClassBDelegate
- (void)delegateMethod;
@end
** classB.m :
@implementation ClassB
.
.
- (void)runClassAMethod
{
     [delegate delegateMethod];
}
.
.
@end
利用delegate来解决类之间相互引用问题(引用死锁),布布扣,bubuko.com
原文:http://www.cnblogs.com/stevenschen/p/3825053.html