2014-12-04 4 views
-1

스위프트으로 코딩 중입니다. 오른쪽에서 왼쪽으로 밀어서 TableViewCell을 삭제하고 싶지만, 즉석이됩니다. 지금은 TableView에서 요소를 제거하는 것 이상의 작업을 수행하고 있습니다. 당신이 볼 수 있듯이, 나는 매우 빠르다 myRecomBottlesArray.removeAtIndex(indexPath.row)tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)TableViewCell 삭제 후 더 많은 작업 수행

// Override to support editing the table view. 
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == .Delete { 

     // Delete the row from the data source 
     myRecomBottlesArray[0].removeFromRecomm(myRecomBottlesArray[indexPath.row]) 
     myRecomBottlesArray.removeAtIndex(indexPath.row) 

     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 

    } else if editingStyle == .Insert { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    } 
} 

: 여기 내 코드입니다.

제 문제는 메모리에서 테이블을로드하고 해당 테이블에서 요소를 제거한 다음 메모리에 테이블을 다시 저장하는 myRecomBottlesArray[0].removeFromRecomm(myRecomBottlesArray[indexPath.row])입니다. 그래서 Delete 버튼을 누르면 버튼을 누른 순간부터 실제로 GUI에서 행을 제거하는 순간까지 2 초의 지연 시간이 있습니다.

먼저 GUI에서 행을 삭제 한 다음 백그라운드에서 내 목록을로드하고 요소를 제거한 다음 목록을 다시 저장하는 방법을 알고 싶습니다. 이렇게하면 사용자는 순간적으로 느껴지고 실제로 앱이 백그라운드에서 수행 될 때 앱에서 계속 작업 할 수 있습니다.

저는 대리인을 사용해야한다고 생각합니다. 그러나 저는 이것에 대해 꽤 새로운데, 어떻게 해야할지 모르겠습니다. 필요한 경우 더 많은 코드를 제공 할 수 있습니다. 여기

removeFromRecomm() 함수의 코드는 다음과 removeFromRecomm 완료 블록 메인 쓰레드 긴 소요

var recomBottlesArray = NSMutableArray()  

func removeFromRecomm(bottle: Bottle) { 
    let bottleLoaded = Bottle.loadSaved() 
    bottleLoaded?.recomBottlesArray.removeObject(bottle) 
    bottleLoaded?.save() 
} 

class func loadSaved() -> Bottle? { 
    if let data = NSUserDefaults.standardUserDefaults().objectForKey("bottleList") as? NSData { 
     return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Bottle 
    } 
    return nil 
} 

func save() { 
    let data = NSKeyedArchiver.archivedDataWithRootObject(self) 
    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "bottleList") 
} 
+0

UI에서 removeFromRecomm 메소드가 모든 작업을 수행합니까? 아니면 모델 만 업데이트합니까? –

+0

UI에서 아무 작업도 수행하지 않습니다. 그것은 메모리 ('NSKeyedArchiver' 더 정확하게) 만 건 드리면됩니다. – magohamoth

답변

0

방법, 즉, 지연의 이유이다.

당신은 그랜드 센트럴 파견을 사용하여 백그라운드 스레드에서 이러한 방법을 실행할 수 있습니다

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { 
    myRecomBottlesArray[0].removeFromRecomm(myRecomBottlesArray[indexPath.row]) 
} 
myRecomBottlesArray.removeAtIndex(indexPath.row) 
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 

또한 NSOperation처럼 백그라운드에서 코드를 실행하는 다른 방법이 있습니다. Concurrency Programming Guide에서 그들에 관해 읽을 수 있습니다. UIKit은 스레드로부터 안전하지 않으므로 UI ​​객체에 대한 모든 작업은 주 스레드에서 수행되어야합니다. 메소드 removeFromRecomm은 모델에서만 작동하기 때문에 백그라운드 스레드에서 호출하는 것이 안전합니다.

+0

고마워요! 나를 위해 일했다 :) – magohamoth

관련 문제