2011年11月29日 星期二

[iOS]Grand Central Dispatch 解決非同步和Multi-thread處理問題

Grand Central Dispatch 是個很重要的Multi-thread的處理方式 但不知道為何在繁體中文資源卻幾乎沒有人提到 是我在看了Beginning iPhone.4 Development Exploring the iOS SDK這本書才知道有這個語法 以往我們在iOS程式設計會很常使用 performSelectorOnMainThread 或是 performSelectorInBackground 等兩個Method 尤其是要更新UI的時候常會使用到, 但是我們因此常要為了更新UI在另外開一個Method來更新UI 造成Trace Code比較困擾 或者是執行某些程式需在Main Thread上時 有個更好的方式應該是用dispatch_async(.....) 這個function來取代會是比較省力的寫法

dispatch_async(dispatch_get_main_queue(),^{
    
    //在Main Thread更新UI
    myLabel.text = "Hello";
     
});


另外一個是非同步等待的問題 例如: 今天我去A和B server取資料,但我想等到A資料和B資料都拿到的時候在程式再繼續跑 就可以使用dispatch_group_async(....)這個function

//建立群組
dispatch_group_t group = dispatch_group_create();


dispatch_group_async(group,dispatch_get_global_queue(0,0),^{
   //從A伺服器取得資料
});

dispatch_group_async(group,dispatch_get_global_queue(0,0),^{
  //從B伺服器取得資料
});

dispatch_group_notify(group,dispatch_get_global_queue(0,0),^{
  //處理A,B資料取得的資料
   
   dispatch_async(dispatch_get_main_queue(),^{
    //在Main Thread更新UI
   });


});

附帶一提在dispatch function裡面所執行的程式都會依照順序來執行 詳細可以參考官方網站的介紹 http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

2011年11月15日 星期二

[iOS]UITextField show behind the Keyboard when editing

當使用UITextField 常會遇要編輯時 被keyborad 擋住了

這時只要將implement UITextFieldDelegate裡的兩個functions 就可解決囉

下面的範例的if是利用UITextField的tag編號去分辨是哪個textField
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag ==1 ) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [self.view setFrame:CGRectMake(self.view.bounds.origin.x , self.view.bounds.origin.y-125, self.view.frame.size.width, self.view.frame.size.height)];
        [UIView commitAnimations];
    }

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"textFieldShouldReturn");
    [textField resignFirstResponder];
    if (textField.tag == 1) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [self.view setFrame:CGRectMake(self.view.bounds.origin.x , self.view.bounds.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
        [UIView commitAnimations];
    }

    
    return NO;
}