Fast way to trim lines at the beginning of a log file on iOS
<p>I'm looking for a fast, optimized way to trim log files on iOS. I want to specify that my log files have a maximum number of lines (e.g., 10,000). Appending new lines to the end of a text file seems relatively simple. However, I haven't yet found a fast way to trim lines at the beginning of the file. Here's the (slow) code I came up with.</p>

<pre><code>    guard let fileURL = self.fileURL else {
        return
    }

    guard let path = fileURL.path else {
        return
    }

    guard let fileHandle = NSFileHandle(forUpdatingAtPath: path) else {
        return
    }

    fileHandle.seekToEndOfFile()
    fileHandle.writeData(message.dataUsingEncoding(NSUTF8StringEncoding)!)
    fileHandle.writeData("\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    currentLineCount += 1

    // TODO: This could probably use some major optimization
    if currentLineCount &gt;= maxLineCount {
        if let fileString = try? NSString(contentsOfURL: fileURL, encoding: NSUTF8StringEncoding) {
            var lines = fileString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
            lines.removeFirst()
            let newData = lines.joinWithSeparator("\n")
            fileHandle.seekToFileOffset(0)
            fileHandle.writeData(newData.dataUsingEncoding(NSUTF8StringEncoding)!)
        }
    }

    fileHandle.closeFile()
</code></pre>