2013-04-01 18 views
-2

我試圖從 - (void)awakeaccelerometer裏面使用randX和randY函數 - 第二個函數 - (void)加速度計..程序無法識別它們。提前致謝。在不同的功能中使用變量? Objective-C

-(void) awakeaccelerometer 
{ 
    [[UIAccelerometer sharedAccelerometer]setUpdateInterval:1.0/50.0]; 
    [[UIAccelerometer sharedAccelerometer]setDelegate:self]; 

    float randX = arc4random() % 320; 
    float randY = arc4random() % 548; 

    CGPoint randNewPlace = CGPointMake(randX, randY); 
    Rand.center = randNewPlace; 

} 


//Controlling the accelerometer 
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
{ 
..... 

CGRect blockRect = CGRectMake(newX, newY, 20, 20); 
CGRect targetRect = CGRectMake(randX, randY, 20, 20); 

    if (CGRectIntersectsRect(blockRect, targetRect)) 
    { 
     float tnewX = arc4random() % 320; 
     float tnewY = arc4random() % 548; 

     CGPoint randNewPl = CGPointMake(tnewX, tnewY); 
     Rand.center = randNewPl; 
    } 


} 
+8

聰明人的話:查找如何[括號](http://aelinik.free.fr/c/ch14.htm)與[類定義(http://developer.apple .com/library/ios /#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html)與[globals](http://stackoverflow.com/questions/3010647/shared-global-variables-in-c)影響變量的範圍。 – CodaFi

+1

這是基本的編程知識,在Objective-C上找到一個教程。你正在尋找的是實例變量。 –

+0

所以我的嵌套函數randX和randY將只使用塊範圍中的同名變量,是否正確? – Apetro

回答

2

你缺少壽命和變量範圍的理解。變量的生命週期是存在並且可以包含值的時間段。變量的範圍是可以訪問變量的代碼範圍。一個變量可以存在但超出範圍(但反之亦然)。

局部變量的壽命randXrandY是從與方法awakeaccelerometer直到awakeaccelerometer特定調用,它創建它們的回報點聲明。這兩個變量的範圍是從聲明點到方法結束的代碼。當CGMakePoint的呼叫在awakeaccelerometer內進行時,兩個變量randXrandY保持活動但超出範圍 - CGMakePoint中的任何代碼都無法引用它們。

兩個變量randXrandY不在accelerometer:didAccelerate:的範圍內。

回答你的問題是,如果你想這兩個變量可用到這兩種方法,那麼你需要將其提升到一個封閉的範圍,使他們都活着,在這兩種方法中的範圍。通常的建議是將它們提升到實例變量(其在一個@interface@implementation的開始的支撐塊中聲明) - 的實例變量的生存期相同的包圍對象,並且在該範圍包括至少該對象的所有實例方法。

但你真的需要明白這是爲什麼,以及是否這是你需要什麼,這些都是任何語言編程的基礎,你應該閱讀並瞭解他們。在所以嘗試搜索「[objective-C]範圍生命週期」,你會得到不少點擊。如果你放下「[objective-C]」,你會得到更多的話題,因爲討論的話題與其他語言有關。在編程(語言概念)的文本中更好看一下,這裏列出的內容太多了!

HTH