使用协议和代理传回数据

时间:2013-06-16 06:02:59

标签: objective-c uiviewcontroller delegates console protocols

我有两个视图控制器:GameFavorites推送SelectFavorites,而我想要做的就是在NSLog上显示我在使用按钮进入SelectFavorites时传回数据。这是我的代码:

SelectFavorites.h

@class SelectFavorites;
@protocol SelectFavoritesDelegate <NSObject>
- (void)addItemViewController:(SelectFavorites *)controller didFinishEnteringItem:    (NSString *)item;
@end


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

@interface SelectFavorites : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, weak) id <SelectFavoritesDelegate> delegate;
- (IBAction)button1:(UIButton *)sender;
@end

SelectFavorites.m

#import "SelectFavorites.h"
#import "GameFavorites.h"



@interface SelectFavorites ()


@end

@implementation SelectFavorites

- (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.

}



- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)button1:(UIButton *)sender {

NSString *itemToPassBack = @"Pass this value back to Gamefavorites";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];


}

@end

GameFavorites.h

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

@interface GameFavorites : UITableViewController <SelectFavoritesDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end

GameFavorites.m

#import "GameFavorites.h"

@interface GameFavorites ()

@end

@implementation GameFavorites


- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {


    SelectFavorites *selectFavorites = [[SelectFavorites alloc]   initWithNibName:@"SelectFavorites" bundle:nil];
    selectFavorites.delegate = self;

[self.navigationController pushViewController:selectFavorites animated:YES];

    // Custom initialization
}
return self;
}



//view did load is called when your view is actually presented onscreen
- (void)viewDidLoad
{
[super viewDidLoad];

}


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



- (void)addItemViewController:(SelectFavorites *)controller didFinishEnteringItem:(NSString *)item
{

NSLog(@"This was returned from ViewControllerB %@",item);


}

当我按下按钮时,我的字符串是否应该显示在控制台中?我没有错误它运行正常,但在控制台中没有任何内容。

一些想法:

  • 推送视图控制器是一个tableview控制器,但我认为这不重要。
  • 也许我的init方法或viewDidLoad方法需要编辑但不确定在哪里。

0 个答案:

没有答案