希望将此处的,多次的save 一个东西的操作:
func storeData(){ dispatchBackground_async({ calcTimeStart("StoreConversationItemList") if self.lastSavedConversationItemCount != self.conversationItemList.count { self.lastSavedConversationItemCount = self.conversationItemList.count //save conversation item into disk for next run app restore if let saveFilePath = getSaveFilePath(ArchiveConversationDir, saveFilename: "conversationItemList") { let saveOk = NSKeyedArchiver.archiveRootObject(self.conversationItemList, toFile: saveFilePath) gLog.info("save conversationItemList \(saveOk) for \(self.conversationItemList.count) items to \(saveFilePath)") } } else { gLog.debug("not saved due to same count of conversation item list") } calcTimeEnd("StoreConversationItemList") } |
合并到一次处理
尤其是发现,之前多次调用的话,其实都是保存的动作,则可以合并为单次的保存即可。
swift merge multiple operation to single
swift multiple operation to single
NSOperation and NSOperationQueue Tutorial in Swift
Core Data Tutorial: Multiple Managed Object Contexts
NSOperationQueue Class Reference
nsoperationqueue 用法
先是用:
var storeDataTimer:NSTimer self.storeDataTimer = NSTimer() func resetStoreDataTimer(){ self.storeDataTimer = NSTimer.scheduledTimerWithTimeInterval(ArchiveSmartSaveDelayTimeInSec, target: self, selector:#selector(ConversationViewController.reallyStoreData), userInfo: nil, repeats: false) } func storeData(){ if self.storeDataTimer.valid { gLog.debug("duplicated call to store data for conversationItemList, so just restart timer") self.storeDataTimer.invalidate() } resetStoreDataTimer() } func reallyStoreData(){ dispatchBackground_async({ calcTimeStart("StoreConversationItemList") //save conversation item into disk for next run app restore if let saveFilePath = getSaveFilePath(ArchiveConversationDir, saveFilename: "conversationItemList") { let saveOk = NSKeyedArchiver.archiveRootObject(self.conversationItemList, toFile: saveFilePath) gLog.info("save conversationItemList \(saveOk) for \(self.conversationItemList.count) items to \(saveFilePath)") } calcTimeEnd("StoreConversationItemList") }) } |
最后是用:
import UIKit class CommonUtil:NSObject { override init() { if smartSaveDict.keys.contains(uniqueId) { if curTimer.valid { let resetedTimer = NSTimer.scheduledTimerWithTimeInterval(ArchiveSmartSaveDelayTimeInSec, target: target, selector:reallySaveData, userInfo: nil, repeats: false) } var gCommonUtil:CommonUtil! func resetCommonUtil() -> CommonUtil { gCommonUtil = CommonUtil() return gCommonUtil } func SingletonCommonUtil() -> CommonUtil { } func storeData(){ SingletonCommonUtil().smartSaveData("conversationItemList", target: self, reallySaveData: #selector(ConversationViewController.reallyStoreData)) } func reallyStoreData(){ } |
去避免多次执行同一个重复动作。
转载请注明:在路上 » [已解决]swift中将多次操作合并到一次处理