2012-05-18 26 views
3

我想做一個iOS應用程序,但我堅持在類之間傳遞數據。 這是我的第二個應用程序。第一個完成了全球班,但現在我需要 多個類。我嘗試了很多教程,但沒有奏效,或者傳遞的值總是爲零。有人可以給我寫一個簡單的應用程序來演示IOS 5中的變量傳遞。 沒什麼特別的,故事板上有兩個視圖控制器,一個變量。Xcode中的類之間的簡單變量傳遞

謝謝你的幫助。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Navigation logic may go here. Create and push another view controller. 

      FirstViewController *fv; 
      fv.value = indexPath.row; 

      NSLog(@"The current %d", fv.value); 

      FirstViewController *detail =[self.storyboard instantiateViewControllerWithIdentifier:@"Detail"]; 
      [self.navigationController pushViewController:detail animated:YES]; 

} 

這裏是從我的主視圖代碼,我需要發送的indexPath.row或細胞的,我壓到下一個視圖

+1

添加你的代碼,你可以得到幫助 - 沒有人會爲你寫一個應用程序 – AnthonyBlake

+0

張貼代碼.... – pie

+0

我正在考慮一個簡單的空白應用程序,但確定,在幾分鐘內即可 – Shawn

回答

12

有幾件事情要做。根據應用程序的不同,您可以向AppDelegate類添加一個變量,通過共享實例使其可用於所有類。最常見的事情(我認爲)是做一個單身人士。爲了達到這個目的,你可以創建一個類,例如StoreVars,以及一個返回對象的靜態方法,這個類使得這個類變得「全局」。在該方法中,您可以像初學者一樣初始化所有變量。那麼你總是可以從任何地方到達他們。

@interface StoreVars : NSObject 

@property (nonatomic) NSArray * mySharedArray; 
+ (StoreVars*) sharedInstance; 

@implementation StoreVars 
@synthesize mySharedArray; 

+ (StoreVars*) sharedInstance { 
    static StoreVars *myInstance = nil; 
    if (myInstance == nil) { 
     myInstance = [[[self class] alloc] init]; 
     myInstance.mySharedArray = [NSArray arrayWithObject:@"Test"]; 
    } 
    return myInstance; 
} 

這將使一個單身人士。如果您記得在兩個viewController中導入「StoreVars.h」,則可以像這樣訪問現在共享的數組;

[StoreVars sharedInstance].mySharedArray; 
      ^

這是返回StoreVars對象的方法。在StoreVars類中,您可以實現任何對象並在靜態方法中初始化它。只要始終記住要初始化它,否則,所有對象都將爲0/nil。

如果你不是UINavigationController的粉絲,而寧願使用segues,它會容易得多,但可以讓你的app變得「雜亂」imo。有一個在UIViewController中,你應該重載實現的方法:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Make sure your segue name in storyboard is the same as this line 
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"]) 
    { 
     // Get reference to the destination view controller 
     YourViewController *vc = [segue destinationViewController]; 

     // Pass any objects to the view controller here, like... 
     [vc setMyObjectHere:object]; 
    } 
} 

來源:How to pass prepareForSegue: an object

問這樣的問題之前做一些研究。閱讀一些教程,並嘗試自己,然後提出有關您真正想要的問題。並不是每個人都想爲你做所有的工作,但有時你很幸運。好像今天。

乾杯。

+0

thnx爲我使用storevars的解決方案,它像一個魅力 – Shawn

1

,如果你使用2個控制器,你必須賽格瑞之間的指數過載prepareToSegue方法

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
// check if it's the good segue with the identifier 
if([[segue identifier] isEqualToString:@"blablabla"]) 
{ 
    // permit you to get the destination segue 
    [segue destinationViewController]; 
    // then you can set what you want in your destination controller 
} 
} 
+1

[segue destinationViewController]; FirstViewController * fv; fv.value = 10; 這樣的事情? – Shawn

+0

你需要在fv.value = 10之前分配你的fv;你需要fv = [segue destinationViewController]; –