ARC issue - cannot pass method to delegate?
Here's my scenario. I have a class A. Inside its implementation I create object of type B and set B's delegate to self (So B.delegate = self
somewhere inside class A's implementation).
And class A has an instance method - (void)printThis;
Now inside B's implementation, when I try to do [delegate printThis];
, it gives me this error:
"No known instance method for selector printThis"
Of course this is when I have enabled ARC. The above delegation pattern used to work fine in iOS 4.x without the ARC. And it still does when I switch OFF ARC. What has ARC got to do with passing messages to delegates?
Skeleton code:
A.h
@class B;
@interface A: blah blah
{
B objB;
}
-(void) 开发者_如何学GoprintThis;
A.m
objB = [[B alloc] init];
objB.delegate = self;
- (void)printThis {
//doSomething
}
B.h
@interface B: blah blah
{
//id delegate; //used to be there, now I just property & synthesize
}
@property (nonatomic,weak) id delegate;
B.m
@synthesize delegate;
[delegate printThis]; //error with ARC ON, works with OFF
IMPORTANT EDIT:
And mind you this happens for a method here and there. For instance I have a few other methods in A like printThat etc etc which work without errors. I'm clueless as to what is happening!
You need to define -printThis
in a protocol and make A implement this protocol. You also need to mark the delegate as conforming to this delegate.
i.e.:
@protocol Printer <NSObject>
- (void)printThis;
@end
@interface A : NSObject <Printer>
//...
@end
@interface B : //...
@property (nonatomic, weak) id<Printer> delegate;
@end
ARC needs to know about the interface for method calls in order to properly manage the memory correctly. If there isn't a definition then it'll complain.
精彩评论