我有一个FirstViewController
和一个SecondViewController
。我在FirstViewController
中创建了一个按钮,以便以模态方式执行到SecondViewController
。
在SecondViewController
中,我有一个tableView显示8个项目的列表,当我从该列表中选择一个项目时,我使用dismissViewControllerAnimated:
返回到FirstViewController
。
我想做的是将一个字符串传回FirstViewController
。
我使用了这篇帖子作为我的代码参考:dismissModalViewController AND pass data back
所以这就是我拥有的:
在FirstViewController.h中
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "SecondViewController.h"
@interface FirstViewController : UIViewController <SecondDelegate>
@end
在FirstViewController.m文件中
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
...
- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
NSString *theString = stringForFirst;
NSLog(@"String received at FirstVC: %@",theString);
}
@end
在SecondViewController.h文件中。
#import <UIKit/UIKit.h>
@protocol SecondDelegate <NSObject>
-(void) secondViewControllerDismissed:(NSString *)stringForFirst;
@end
@interface SecondViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
__weak id myDelegate;
}
@property (nonatomic, weak) id<SecondDelegate> myDelegate;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end
在SecondViewController.m文件中
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize myDelegate;
@synthesize myTableView;
...
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [atributoTableView dequeueReusableCellWithIdentifier:@"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
}
cell.textLabel.text = //strings from an array here;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:)])
{
[self.myDelegate secondViewControllerDismissed:@"SOME STRING HERE"];
NSLog(@"string passed");
}
[self dismissViewControllerAnimated:YES completion:nil];
NSLog(@"SecondViewController dismissed");
}
@end
当我运行应用程序时,我可以从
FirstViewController
转到SecondViewController
,当我从tableView中选择一行时,我可以很好地返回FirstViewController
。问题是字符串“SOME STRING HERE”没有传回。我错过了什么?
顺便说一下,我不确定这是否相关:我正在使用ARC和Storyboards。
[self.myDelegate secondViewControllerDismissed ...
这一行? - iDev