sia*_*sia 16 iphone algorithm search ios swift
我有情况在哪里我必须搜索**路由器**的IP地址,我知道它的范围是从范围163.289.2.0到163.289.2.255.我知道这不是搜索的好方法.
for i in 1... 255 {
var str = "163.289.2." + "i"
var tempIP = Ping.getIPAddress(str)
if(tempIP == true)
{
break;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我的自定义类Ping.getIPAddress()需要3秒才能获得给定IP值的结果.因此,对于255次搜索,大约需要765秒(12.75分钟).我有限制搜索应该在最多2分钟内完成.所以无论如何我可以使用swift在iPhone中实现这一点.
我必须只使用这个自定义函数Ping.getIPAddress(),如果存在给定的IP地址则为true,否则为false.
请提供解决此问题的示例或参考或方法.
使用NSOperationQueue和MaxConcurrentOperationCount设置为10会不错?
Luc*_*tti 14
如果我们Ping.getIPAddress(str)只在前一个完成后执行每个调用当然我们需要等待(3秒*256)= 768秒.
另一方面,我们可以执行多个并发调用Ping.getIPAddress(str).
这是我为测试你的功能而创建的一个类.
class Ping {
class func getIPAddress(str:String) -> Bool {
sleep(3)
return str == "163.289.2.255"
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的类并等待3秒(以模拟您的情况),然后返回true仅当传递ip的163.289.2.255.这允许我复制最坏的情况.
这是我准备的课程
class QuantumComputer {
func search(completion:(existingIP:String?) -> ()) {
var resultFound = false
var numProcessed = 0
let serialQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL)
for i in 0...255 {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0)) {
var ip = "163.289.2." + "\(i)"
let foundThisOne = Ping.getIPAddress(ip)
dispatch_async(serialQueue) {
if !resultFound {
resultFound = foundThisOne
numProcessed++
if resultFound {
completion(existingIP:ip)
} else if numProcessed == 256 {
completion(existingIP: nil)
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该类执行256异步调用到Ping.getIPAddress(...).
256个异步闭包的结果由以下代码处理:
dispatch_async(serialQueue) {
if !resultFound {
resultFound = foundThisOne
numProcessed++
if resultFound {
completion(existingIP:ip)
} else if numProcessed == 256 {
completion(existingIP: nil)
}
}
}
Run Code Online (Sandbox Code Playgroud)
前一个代码块(从第2行到第9行)在我的队列中执行serialQueue.这里256个不同的闭包同步运行.
resultFound和numProcessed;这就是我从标准ViewController中调用它的方式.
class ViewController: UIViewController {
var computer = QuantumComputer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
debugPrintln(NSDate())
computer.search { (existingIP) -> () in
debugPrintln("existingIP: \(existingIP)")
debugPrintln(NSDate())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)
最后,这是我在iOS模拟器上测试时的输出.请注意,这是最糟糕的情况(因为上次检查的号码是有效的IP).
2015-09-04 20:56:17 +0000
"existingIP: Optional(\"163.289.2.255\")"
2015-09-04 20:56:29 +0000
Run Code Online (Sandbox Code Playgroud)
这只有12秒!
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
694 次 |
| 最近记录: |