我有同樣的問題......通過噸教程和書籍的工作。這是爲我工作的。它混合了兩種方法,可能只需要一種。但至少我瞭解它並可以輕鬆使用它。這些方法是委派並使用單例來保存您的全局變量。
我將我的代碼粘貼到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
所有其他viewcontrollers可以看到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);
}
的賽格瑞標識是通過點擊SEGUE,在屬性檢查器將其命名上的腳本輸入。完成的方法將在TableViewController關閉時調用。它在這裏表示的是行值,以證明原始視圖控制器知道該行。你的代碼會從那裏拿走它(如果你願意,你可以傳遞數據)...你必須爲此聲明合適的全局變量。)
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];
}
你走了......我希望我找到了適用於你的情況的工作程序中的所有代碼。對不起,如果我省略了什麼
-Rob
您使用的是什麼類型的segue?推或模態? – Rakesh 2013-03-02 15:57:47
我正在使用推送 – aburb 2013-03-02 16:11:57
其實,沒關係。訣竅是能夠訪問第一個視圖控制器中的變量(想要傳遞的值)。答案中解釋瞭解決此問題的一種方法。另一種方法是使用應用程序委託或全局可訪問的對象來存儲變量。 – Rakesh 2013-03-02 16:14:42