Order a NSURL array

谁说我不能喝 提交于 2019-12-23 01:17:09

问题


I'm loading a lot of image paths into a NSURL. The images are in a folder ordered from 1.PNG, 2.PNG, 3.PNG to 1500.PNG.
When I trie to load them:

let imagePath = path + "/images"
        let url = NSURL(fileURLWithPath: imagePath)
        print(url)
        let fileManager = NSFileManager.defaultManager()
        let properties = [NSURLLocalizedLabelKey,
                          NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]

        do {
            imageURLs = try fileManager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)
        } catch let error1 as NSError {
            print(error1.description)
        }

The imageURLs array gets filled with:

imageURLs[0] = ...\0.PNG
imageURLs[1] = ...\1.PNG
imageURLs[2] = ...\100.PNG
imageURLs[3] = ...\1000.PNG

and not in the numeric order!
Can someone help to sort the imageURLs or while i load the image paths on it or after they are loaded?


回答1:


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.



来源:https://stackoverflow.com/questions/38819395/order-a-nsurl-array

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