邮件转发不起作用(Objective-C)

时间:2019-01-31 07:50:46

标签: ios objective-c invocation message-forwarding

我正在编写示例代码,以了解Objective C(iOS)中的消息转发。

我有两个班级(A级和B级)。我想创建一个类B的实例,并为其设置一个类A的实例变量。我在以下代码中调用转发调用方法(消息转发)。

//  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

我希望上面的代码能正常工作。但是相反,我得到了以下构建时间错误:

ARC语义问题 TestInvocation.m:19:35:“ ClassB”没有可见的@interface声明选择器“值”

1 个答案:

答案 0 :(得分:0)

B类至少应在接口中具有该属性。 但是,如果要调用forwardInvocation,可以在实现中将其设置为@dynamic。

@interface ClassB : NSObject
@property (readwrite, assign) int value;
@end

@implementation ClassB
@dynamic value;
...
@end

我认为它应该对您有用。