2011-06-01 41 views
1

下面的代碼是從開始Iphone 4開發的搖動和烘焙示例的近似複製品。它在CMA加速加速= accelerometerData.acceleration之前缺少BOOL if語句;因爲我希望這個人可以隨意多次動搖和刷新結果。我有一個按鈕,可以完美地執行相同的代碼。當我運行代碼並搖動iPhone時,它會崩潰。我錯過了什麼會使這項工作?你不能像搖動方法一樣使用按鈕來運行相同的代碼嗎?從'開始Iphone 4開發'調整搖碼導致崩潰

example.h文件

#import <CoreMotion/CoreMotion.h> 
#define kAccelerationThreshold 1.7 
#define kUpdateInterval (1.0f/10.0f) 

@interface exampleViewController : UIViewController { 
CMMotionManager *motionManager; 
} 
@property (retain,nonatomic) CMMotionManager *motionManager; 
@end 

Example.m

@synthesize motionManager; 

-(void)viewDidLoad { 

self.motionManager = [[[CMMotionManager alloc] init] autorelease]; 
motionManager.accelerometerUpdateInterval = kUpdateInterval; 
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; 
[motionManager startAccelerometerUpdatesToQueue:queue 
            withHandler: 
^(CMAccelerometerData *accelerometerData, NSError *error){ 
    if (error) { 
     [motionManager stopAccelerometerUpdates]; 
    } else { 
     CMAcceleration acceleration = accelerometerData.acceleration; 
     if (acceleration.x > kAccelerationThreshold 
      || acceleration.y > kAccelerationThreshold 
      || acceleration.z > kAccelerationThreshold){ 

// There is a bunch of other stuff here, but it all works using a button called shake.... 
      example4.hidden = NO; 
      select1.text = first; 
      display.text = [[NSString alloc] initWithFormat: @"%@", first]; 

     } 
    } 
}]; 
} 

- (void)dealloc 
{ 
[super dealloc]; 
[motionManager release]; 
} 

- (void)viewDidUnload { 
[super viewDidUnload]; 
self.motionManager = nil; 
} 

@end 
+0

這幫助我實現了使用CoreMotion框架的搖動手勢,我無法在Google搜索 - > Stackoverflow上找到它。您應該添加它作爲答覆的一個帖子詢問如何做到這一點。 – Kunalxigxag 2014-01-24 06:22:35

回答

1

您正試圖創建和顯示上比主線程的線程上的警報視圖。 UI更新只能在主線程中完成。您應該使用performSelectorOnMainThread:withObject:waitUntilDone:在主線程上創建並顯示。

您可以隨時添加請求您的UI更新這樣的 -

dispatch_async(dispatch_get_main_queue(),^{ 
    // Put all your UI updates here; 
}); 
+0

嗯,我想我忽略了這一點,因爲我的真實代碼是隱藏圖像,顯示UILabel上的數組中的文本,並在UITextView上顯示文本。這是否仍然適用於警報視圖以外的輸出?現在我想到了,該應用剛剛與其他代碼崩潰。我會編輯這個問題,使其更清晰,更具象徵性。 – StreaminJA 2011-06-01 19:41:46

+0

它們仍然是UI更新的權利?而且他們正在其他不安全的線程上完成。 – 2011-06-01 20:07:15

0

,看起來腥我是NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];的一部分。

在motionManager分派給它的時間內,你無處掛上隊列。我檢查了startAccelerometerUpdatesToQueue的文檔,但沒有說接收者保留了隊列,所以這可能不是您可以安全地假設的。我的建議是不要自動釋放隊列。在調用motionManager上的stopAccelerometerUpdates之後,在viewDidUnload中釋放它。