I am writing a sample code in order to understand message forwarding in Objective C (iOS).
I have two classes (class A and class B). I want to create an instance of class B and set a class A instance variable to it. I am calling the Forward Invocation method (Message Forwarding) in the following code.
// ViewController.h
// TestInvocation
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
// TestInvocation
#import "ViewController.h"
#import "TestInvocation.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[TestInvocation testRun];
[super viewDidLoad];
}
@end
// TestInvocation.h
// TestInvocation
#import <Foundation/Foundation.h>
@interface TestInvocation : NSObject
{}
+(void)testRun;
@end
// TestInvocation.m
// TestInvocation
#import "TestInvocation.h"
#import "ClassB.h"
#import "ClassA.h"
@implementation TestInvocation
+(void)testRun
{
ClassB* diplomat = [[ClassB alloc] init];
NSLog(@"value = %d",[diplomat value]);// Error shows up here on running:
//No visible @interface for 'ClassB' declares the selector 'value'
}
@end
// ClassA.h
// TestInvocation
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
{
int value;
}
@property(readwrite,assign) int value;
@end
// ClassA.m
// TestInvocation
#import "ClassA.h"
@implementation ClassA
@synthesize value;
@end
// ClassB.h
// TestInvocation
#import <Foundation/Foundation.h>
@interface ClassB : NSObject
{}
@end
// ClassB.m
// TestInvocation
#import "ClassB.h"
#import "ClassA.h"
@implementation ClassB
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
return [ClassA instanceMethodSignatureForSelector:aSelector];
}
-(void)forwardInvocation:(NSInvocation *)anInvocation
{
ClassA* negotiate = [[ClassA alloc] init];
negotiate.value = 15;
[anInvocation invokeWithTarget:negotiate];
}
@end
I am expecting the above code to work. But instead I get the following build time error:
ARC Semantic Issue TestInvocation.m:19:35: No visible @interface for 'ClassB' declares the selector 'value'
Class B should have the property in interface at least. But you can make it @dynamic in implementation if you want to call forwardInvocation.
I think it should work for you.