让委托在两个视图控制器之间工作

时间:2012-10-23 04:06:44

标签: iphone ios delegates protocols

我是iPhone开发的新手,并且有一些关于protocolsdelegates的基本问题。我有两个视图控制器:视图控制器和viewcontroller2nd。我在其中一个中有 UITextField ,并想在其中输入内容(如名称),在viewcontroller2nd中,我有一个 UILabel ,我希望它出现您好,更改UITextField时的名称。

我正在关注此视频:http://www.youtube.com/watch?v=odk-rr_mzUo以使基本委托在单个视图控制器中工作。

我正在使用协议来实现这个:

SampleDelegate.h

#import <Foundation/Foundation.h>

@protocol ProcessDelegate <UITextFieldDelegate>
@optional
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
@end

@interface SampleDelegate : NSObject
{
    id <ProcessDelegate> delegate;
}

@property (retain) id delegate;

@end

SampleDelegate.m

#import "SampleDelegate.h"

@implementation SampleDelegate

@synthesize delegate;

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    lbl.text = [NSString stringWithFormat:@"Hello, %@",txtField.text];
    [txtField resignFirstResponder];

}

@end

ViewController.h

#import <UIKit/UIKit.h>
#import "SampleDelegate.h"

@interface ViewController : UIViewController <ProcessDelegate>
{
    IBOutlet UITextField *txtField;
}

@end

Viewcontroller.m

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

ViewController2nd.h

#import <UIKit/UIKit.h>

@interface ViewController2nd : UIViewController <ProcessDelegate> {

    IBOutlet UILabel *lbl;
}



@end

ViewController2nd.m 是Xcode的标准代码。

我的问题是如何将我的委托功能链接到我的viewcontroller和viewcontroller2nd以使其工作?

请原谅我,如果问题是愚蠢的......需要一些指导。请指出我正在做的任何其他错误..谢谢..

1 个答案:

答案 0 :(得分:1)

贵国代表团有点......关闭。

首先:不要通过协议继承覆盖UIKit委托方法。这是毫无意义。为什么不首先让你的类符合指定的委托?

@protocol ProcessDelegate //No more protocol inheritance!
 //...
@end

其次:当一个对象定义了一个协议时,该对象的有效实例必须由其委托使用(或者至少传递给它)。所以,任何希望成为SampleDelegate代表的人(顺便说一下,对于 来说真的是一个坏名称)会初始化一个有效的{{1} } object,并调用SampleDelegate,就像它是任何其他属性一样。

-setDelegate:

第三:你实际上没有定义任何委托方法!如果没有任何代表权,授权的重点是什么!l

//#import "SampleDelegate"
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //make this a property, so it isn't crushed when the function exits.
    SampleDelegate *myDelegateObject = [[SampleDelegate alloc]init];
    [myDelegateObject setDelegate:self];  //conform to the delegate
}

第四,也是最重要的: 永远不会永远使用@protocol ProcessDelegate -(void)someMethod; @end retain存储说明符与代表! 委托对象应该是strongweak,以防止令人讨厌的保留周期。

assign
相关问题