【发布时间】:2011-05-13 12:47:56
【问题描述】:
我创建了这个测试用例作为我的问题的一个简单示例。
- AppDelegate 初始化 TestViewController 并将其添加到窗口中
- TestViewController 初始化 TestView 并使其成为视图
- TestView 初始化 TestSubView 并将其添加为子视图
我的目标是允许 TestSubView 通过委托访问 TestViewController 的方法和变量。在此示例中,TestSubView 通过 touchesBegan 或 touchesMoved 访问方法。
请帮忙。谢谢。
编辑:尽管没有更多错误,但仍然不起作用。我所做的:将协议定义移动到一个单独的文件并导入它,保留分配,并删除标题开头的@protocol TestDelegate 声明。
我认为我的问题是我没有在 TestViewController.m 中分配委托,如果这是问题我该怎么做?
TestViewController.h
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController <TestDelegate> {
int number;
}
-(void)assignNumber:(int)value;
-(void)displayNumber;
@property int number;
@end
移至 protocol.h 并在需要的地方导入
@protocol TestDelegate
-(void)assignNumber:(int)value;
-(void)displayNumber;
@end
TestViewController.m
#import "TestViewController.h"
#import "TestView.h"
@implementation TestViewController
@synthesize number;
- (void)loadView {
TestView *myView = [[TestView alloc] initWithFrame:CGRectMake(0,0,320,480)];
self.view = myView;
[myView release];
}
-(void)assignNumber:(int)value {
NSLog(@"Number Assigned");
number = value;
}
-(void)displayNumber {
NSLog(@"%i",number);
}
TestSubView.h
#import <UIKit/UIKit.h>
#import "TestViewController.h"
@interface TestSubView : UIView {
id<TestDelegate> delegate;
}
@property (nonatomic, retain) id<TestDelegate> delegate;
@end
TestSubView.m
#import "TestSubView.h"
#import "TestViewController.h"
@implementation TestSubView
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
[self setBackgroundColor:[UIColor redColor]];
[self setUserInteractionEnabled:YES];
}
return self;
}
- (void)dealloc {
[super dealloc];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.delegate assignNumber:5];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self.delegate displayNumber];
}
【问题讨论】:
-
在协议中声明方法时,不需要在符合协议的类中再次声明这些方法。 (实际上,您不应该这样做,因为如果您更改其中一个而不更改另一个,这会导致稍后出现不匹配错误。)另外,为什么
assignNumber:?我建议只在协议中声明该属性。 -
你能添加你的TestView类吗?这就是这里缺少的胶水,可能是您的问题所在。
-
TestSubView 的意思是 TestView 吗?
标签: iphone cocoa cocoa-touch delegates protocols