2015-10-29 4 views
-1

Я пытаюсь получить строку из контроллера представления к другому с помощью делегата method.But метод делегата не получает called.Below это кодObjective C-пользовательский делегат не работает

@protocol CustomDelegate<NSObject> 
    -(void)didDataRecieved; 
@end 

@interface CustomController:UIViewController 
@property id<CustomDelegate>delegate; 
@property(retain,nonatomic)NSString *string; 
@end 

@implementaion CustomController 
-(void)viewDidLoad 
    { 
    [email protected]"hello"; 
    if([self.delegate [email protected](didDataRecived)]) { 
     [self.delegate didDataRecieved]; 
    } 
    } 

-(IBACTION)gotoViewController 
{ 
    ViewController *view=[self.storyboard instantiateViewController:@"View"]; 
    [self.navigationController pushViewController:view aniamted:YES]; 
} 
@end 

@interface ViewController:UIViewController<CustomDelegate> 
@property (nonatomic,retain)CustomController *cust; 
@end 

@implementation ViewController 
-(void)viewDidLoad 
{ 
    self.cust=[[CustomController alloc]init]; 
    self.cust.delegate=self; 
} 

-(void)didDataRecieved 
{ 
    NSLog(@"data %@",self.cust.string); 
} 
@end 

Может кто-нибудь точку где я ошибаюсь ... plz help.

отредактировал код .. попробовал этот путь тоже.

if([self.delegate [email protected](didDataRecived)]){ 
    [self.delegate didDataRecieved]; 
    } 
+1

Вы толкание/представляя свой 'CustomController' где-нибудь? – Vijay

+0

Вы уверены, что вызывается 'viewDidLoad'? Откуда вы знаете? – Arc676

+0

попробовать контрольную точку внутри 'didDataRecieved' – abhi1992

ответ

1

Я дам вам образец кодирования. Настройте приведенный ниже код.

Здесь у нас есть два контроллера вида.

ViewController и SecondViewController

в SecondViewController

.h

#import <UIKit/UIKit.h> 
@class SecondViewController; 
@protocol SecondViewControllerDelegate <NSObject> 
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text; 
@end 
@interface SecondViewController : UIViewController 
@property (nonatomic, assign)id<SecondViewControllerDelegate> delegate; 
@property (nonatomic, strong) IBOutlet UITextField *nameTextField;//It must connect as outlet connection 
- (IBAction)doneButtonTapped:(id)sender; 
@end 

.m

#import "SecondViewController.h" 
@interface SecondViewController() 
@end 
@implementation SecondViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
    // Custom initialization 
    } 
    return self; 
} 

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

//Either use NSNotification or Delegate 
- (IBAction)doneButtonTapped:(id)sender; 
{ 
      //Use Notification 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passingDataFromSecondViewToFirstView" object:self.nameTextField.text]; 
      //OR Custom Delegate 
    [self.delegate secondViewController:self didEnterText:self.nameTextField.text]; 
    [self.navigationController popViewControllerAnimated:YES]; 
} 
- (void)didReceiveMemoryWarning 
{ 
     [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
} 

в ViewController

.h

#import <UIKit/UIKit.h> 
#import "SecondViewController.h" 
@interface ViewController : UIViewController<SecondViewControllerDelegate> 
@property (nonatomic, strong) IBOutlet UILabel *labelName; //You must connect the label with outlet connection 
- (IBAction)gotoNextView:(id)sender; 
@end 

.m

#import "ViewController.h" 
@interface ViewController() 
@end 
@implementation ViewController 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    //addObserver here... 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFromPreviousViewControllerNotificationReceived:) name:@"passingDataFromSecondViewToFirstView" object:nil]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

//addObserver Method here.... 
- (void)textFromPreviousViewControllerNotificationReceived:(NSNotification *)notification 
{ 
    // set text to label... 
    NSString *string = [notification object]; 
    self.labelName.text = string; 
} 
- (IBAction)gotoNextView:(id)sender; 
{ 
    //If you use storyboard 
    SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"]; 
    //OR If you use XIB 
    SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; 
    secondViewController.delegate = self; 
    [self.navigationController pushViewController:secondViewController animated:YES]; 
} 

//Calling custom delegate method 
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text 
{ 
    self.labelName.text = text; //Getting the data and assign the data to label here. 
} 

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

Для вашего понимания кода я создаю простой передачи данных из одного второго контроллера представления на первый контроллер представления.

Сначала мы перемещаем представление от контроллера первого взгляда до второго контроллера.

После этого мы отправляем данные с контроллера второго вида на контроллер первого вида.

Примечание: Вы можете использовать метод NSNotification или пользовательский делегат для передачи данных от одного View Controller для другого View Controller

Если вы используете NSNotification, вам необходимо установить postNotificationName для получения данных в кнопке способ действия.

Далее вам нужно написать addObserver (отправка данных в требуемый контроллер просмотра) ViewController и вызов метода addObserver в том же контроле View.

Если вы используете пользовательский делегат, Обычно мы идем с пользовательского протокола делегатом, а также мы должны Присвоить делегат здесь.

Очень важно, мы должны установить пользовательский делегат метода в Второй View Controller .because где мы отправляем данные в первый контроллер представления один раз кликаем кнопку Готово во втором контроллере представления.

Наконец, мы должны вызвать пользовательский делегат метода в First View Controller, где мы получаем данные и назначить эти данные для label.Now вы можете увидеть передаваемые данные, используя пользовательский делегат.

Аналогично вы можете отправить данные в другой контроллер представления с использованием пользовательского делегат Методы

+0

спасибо за ответ, он сработал – Prarthana

0

Как вы нажимаете свой второй контроллер? я не могу видеть. , но ваш код работает для меня.

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    ViewController1 *vc = [ViewController1 new]; 
    vc.delegate = self; 
    [self presentViewController:vc animated:YES completion:nil]; 
} 

-(void)didDataRecieved 
{ 
    NSLog(@"recieved"); 
} 

@end 
+0

с использованием push - ViewController * view = [self.storyboard instantiateViewController: @ "View"]; [self.navigationController pushViewController: просмотр aniamted: YES]; – Prarthana

+0

self.cust = [[CustomController alloc] init]; и ViewController * view = [self.storyboard instantiateViewController: @ "View"]; это разные случаи! при представлении контроллера вы не назначаете ссылку делегата. перед тем, как делать. использовать view.delegate = self – rsdk

Смежные вопросы