1

私はiPhone開発の初心者であり、いくつかの基本的な質問がprotocolsありdelegatesます。私は2つのビューコントローラーを持っています:ビューコントローラーとviewcontroller2nd。そのうちの1つにUITextFieldがあり、そこに何か(名前など)を入力したいと思います。viewcontroller2ndにUILabelがあり、UITextFieldが変更されたときに名前をHelloとして表示したいと思います。

私はこのビデオをフォローしています: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にリンクして、それを機能させるにはどうすればよいですか?

質問がばかげているなら、私を許してください。いくつかのガイダンスが必要です。私がしている他の間違いを私に指摘してください..ありがとう..

4

1 に答える 1

1

あなたの代表団は少し...オフです。

まず、プロトコルの継承を通じてUIKitデリゲートメソッドをオーバーライドしないでください。それは無意味です。そもそも、クラスを指定されたデリゲートに準拠させてみませんか?

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

次に、オブジェクトがプロトコルを定義した場合、そのオブジェクトの有効なインスタンスがそのデリゲートによって使用されている(または少なくとも渡されている)必要があります。したがって、デリゲートになりたいもの(ちなみに、クラスSampleDelegateの名前は本当に悪い)は、有効なオブジェクトを初期化し、他のプロパティであるかのように呼び出します。 SampleDelegate-setDelegate:

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

第三に、実際にはデリゲートメソッドを定義していません!委任するものがない場合の委任のポイントは何ですか!l

@protocol ProcessDelegate 
 -(void)someMethod;
@end

第4に、そして最も重要なこと:デリゲートで、またはストレージ指定子を使用することは決してありません。retainstrong デリゲートオブジェクトは、厄介な保持サイクルを防止するために使用されweakます。assign

@property (assign, nomatomic) id delegate;
于 2012-10-23T04:18:03.657 に答える