Order a NSURL array

你离开我真会死。 提交于 2019-12-06 11:18:01

As you want to sort the files by the number you have to parse first the path to achieve it, so let's suppose we have the following array of NSURL objects:

var urls = [NSURL(string: "file:///path/to/user/folder/2.PNG")!, NSURL(string: "file:///path/to/user/folder/100.PNG")!, NSURL(string: "file:///path/to/user/folder/101.PNG")!, NSURL(string: "file:///path/to/user/folder/1.PNG")! ]

We can use the pathComponents property to extract an array with all the components in the path for a NSURL (e.g ["/", "path", "to", "user", "folder", "2.PNG"]).

If we see we can order the files by the last element in the array that is the filename removing the extension and the dot("."), in this case the number. Let's see how to do it in the following code:

urls.sortInPlace {

   // number of elements in each array
   let c1 = $0.pathComponents!.count - 1
   let c2 = $1.pathComponents!.count - 1

   // the filename of each file
   var v1 = $0.pathComponents![c1].componentsSeparatedByString(".")
   var v2 = $1.pathComponents![c2].componentsSeparatedByString(".")

   return Int(v1[0]) < Int(v2[0])
}

In the above code we use the function sortInPlace to avoid create another array with the elements sorted, but can you use sort instead if you want. The another important point in the code is the line return Int(v1[0]) < Int(v2[0]), in this line we have to convert the number in the string to a real number, because if we compare the two strings "2" and "100" the second one is less than greater than because the string are compared lexicographically.

So the the array urls should be like the following one:

[file:///path/to/user/folder/1.PNG, file:///path/to/user/folder/2.PNG, file:///path/to/user/folder/100.PNG, file:///path/to/user/folder/101.PNG]

EDIT:

The two functions pathComponents and componentsSeparatedByString increase the space complexity of the sortInPlace algorithm, if you can asure that the path for the files always will be the same except it's filename that should be a number you can use instead this code:

urls.sortInPlace { $0.absoluteString.compare(
                   $1.absoluteString, options: .NumericSearch) == .OrderedAscending
}

I hope this help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!