我也遇到了同样的问题……阅读了大量的教程和书籍。这对我有用。它混合了两种方法,可能只需要一种。但至少我理解它并且可以轻松使用它。这些方法是委托和使用单例来保存您的全局变量。
我将代码粘贴到 Word 中,删除了不适用的内容,并留下了您需要的所有内容。
首先,创建一个新的类文件。我的叫做 OptionsSingleton。这为您提供了 OptionsSingleton.h 和 OptionsSingleton.m。
我的有更多变量,但以下是适用于您的:
OptionsSingleton.h
@interface OptionsSingleton : NSObject{
int gblRowPicked;
}
@property(nonatomic) int gblRowPicked;
+(OptionsSingleton *) singleObj;
@end
OptionsSingleton.m
#import "OptionsSingleton.h"
@implementation OptionsSingleton
{
OptionsSingleton * anotherSingle;
}
@synthesize gblRowPicked;
+(OptionsSingleton *)singleObj{
static OptionsSingleton * single=nil;
@synchronized(self)
{
if(!single)
{
single = [[OptionsSingleton alloc] init];
}
}
return single;
}
@end
如果您告诉他们单例的存在,所有其他视图控制器都可以看到 gblRowPicked。
// ViewControllerThatCallsTheTableViewController.h
#import <UIKit/UIKit.h>
#import "OptionsSingleton.h"
@interface ViewControllerThatCallsTheTableViewController.h : UIViewController
{
OptionsSingleton *optionsSingle;
}
还有……
// ViewControllerThatCallsTheTableViewController.m
#import "ViewControllerThatCallsTheTableViewController.h"
#import "OptionsSingleton.h"
@interface ViewControllerThatCallsTheTableViewController ()
@end
@implementation ViewControllerThatCallsTheTableViewController
- (void)viewDidLoad
{
optionsSingle = [OptionsSingleton singleObj];
[super viewDidLoad];
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"PickFromTable"]){
TableViewController *viewController = segue.destinationViewController;
viewController.delegate = self;
}
}
-(void)done{
[self dismissViewControllerAnimated:YES completion: nil];
NSLog (@"Back in ViewControllerThatCallsTableViewController, Row picked is %i",optionsSingle.gblGamePicked);
}
通过单击转场并在属性检查器中命名转场,在情节提要中输入转场标识符。关闭时 TableViewController 将调用 done 方法。这里所说的只是行值,以证明原始视图控制器知道该行。您的代码将从那里获取它。(如果需要,您可以传递行中的数据...您必须为此声明适当的全局变量。)
TableViewController 文件中有这些东西:
// TableViewController.h
@protocol ViewControllerThatCallsTheTableViewControllerDelegate <NSObject>
-(void) done;
@end
@interface TableViewController
协议告诉 TableViewController “完成”方法在原始视图控制器中,而不是在 TableViewController 本身中。
// TableViewController.m
#import "TableViewController.h"
#import "BeginningCell.h" // used for the prototype cell
#import "OptionsSingleton.h"
@interface TableViewController ()
@end
@implementation TableViewController
- (void)viewDidLoad
{
optionsSingle = [OptionsSingleton singleObj];
//other stuff: arrays for filling the table, etc.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
optionsSingle.gblRowPicked=indexPath.row+1;
[self.delegate done];
}
你去...我希望我在我的工作程序中找到了适用于你情况的所有代码。对不起,如果我遗漏了什么。
-罗伯