在iOS中高效同步数据 [英] Efficiently sync data in iOS

查看:153
本文介绍了在iOS中高效同步数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,当应用程序进入后台并且应用程序处于活动状态时,我会与服务器之间来回同步数据.因为当我同步到多个设备时,应该在所有设备上更新数据.

I am working on app where I sync data to and from the server, when app enters background and app becomes active. Because as I sync to multiple devices, the data should be updated on all devices.

这就是我的做法,

- (void)applicationDidBecomeActive:(UIApplication *)application
{
     if([[AppManager instance].globalManager activeSyncCounter] == 0)
     {
           [_webService callServerAPI];         
     }
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if([[AppManager instance].globalManager activeSyncCounter] == 0)
     {
           [_webService callServerAPI];         
     }
}

让我解释一下上面的代码

Let me explain the code above

1)我正在调用API来同步我的数据,我迭代了for循环以同步我的数据并将其发送到服务器.(所有调用都是异步的)

1) I am calling APIs to sync my data, I iterate through the for loop to sync my data and send it to server.( all calls are async)

2)如您所见,我已经使用了 activeSyncCounter .我之所以这样使用,是因为用户可以立即打开和退出该应用程序,这样在第一个完成之前,不会再次调用服务器API.

2) As you can see I have used activeSyncCounter. I have used this because, user can open and exit the app immediately, so that server APIs are not called again, till first one finishes.

现在这是我的疑问.

1)首先,当我收到来自服务器的响应时,当数据更多时,通过for循环进行更新需要花费时间,并且我的UI变得无响应. 因此,为了改善这一点,我需要在分派队列中运行for循环代码. 还是他们有其他更好的方法吗?

1) Firstly when I receive response from server, when the data is more, it takes times to update going through the for loop, and my UI becomes unresponsive. So for this to improve, I need to run the for loop code inside a dispatch queue. Or is their any other better way to do it?

此外,当更新完成后,当应用程序进入后台时,我是否需要在应用程序进入后台时调度队列?

Also, as updating is done, when app enters background, so do I need dispatch queue when app enters background?

2)其次,它们是使用 activeSyncCounter

2) Secondly, is their any alternative for using activeSyncCounter

推荐答案

您(几乎)永远不想在主线程上执行任何同步的I/O操作(包括网络操作),所以对您来说,第一个问题是,您应该使用异步联网API或将同步操作移到另一个线程上,派遣队列是实现此目的的一种方法.

You (almost) never want to do any synchronous I/O operations (including network operations) on the main thread, so to you first question, yes, you should either use asynchronous networking APIs or move the synchronous operation to a different thread -- dispatch queues are one way to do that.

关于您的第二个问题,我不知道肯定存在更好"的方式,但是有不同的方式.我可能建议的一件事是将检查移到callServerAPI中,以简化调用该方法的代码. (即,一次编写检查代码,而不是在调用服务器API的任何地方编写代码.)

As to your second question, I don't know that there's definitively a "better" way, but there are different ways. One thing that I might suggest would be to move that check into callServerAPI so as to simplify the code that calls that method. (i.e. write the checking code once, instead of everywhere you call the server API.)

这篇关于在iOS中高效同步数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆