2017-10-21 177 views
0

我嘗試使用下面的代碼它在哪裏來從.document的URL用於快框架表視圖錯誤致命錯誤:超出範圍的索引加載文件

準備URL路徑加載到我的tableview時空當它第一次創建

var fileURLs = [NSURL]() 

然後

private func prepareFileURLS() { 
    let csvFile = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL 
    if FileManager.default.fileExists(atPath: csvFile.path) { 
     fileURLs.append(csvFile as NSURL) 
     print(fileURLs) 
    } 
} 

然後使用下面的代碼給標籤的名稱

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let objectIdentifier = "ObjectsTableViewCell" 

    guard let cell = tableView.dequeueReusableCell(withIdentifier: objectIdentifier, for: indexPath) as? ObjectsTableViewCell else { 
     fatalError("The dequeued cell is not an instance of ObjectsTableViewCell") 
    } 

    //quickview 
    // Fetches the appropriate object for the data source layout 
    let currentFileParts = extractAndBreakFilenameInComponents(fileURL: fileURLs[indexPath.row]) 

    cell.nameLabel.text = currentFileParts.fileName 
    //cell.photoImageView.image = cur.photo 
    //quickview 
    cell.descriptionLabel.text = getFileTypeFromFileExtension(fileExtension: currentFileParts.fileExtension) 

    return cell 
} 

,並使用下面的方法來打破路徑轉換爲字符串它導致錯誤

private func extractAndBreakFilenameInComponents(fileURL: NSURL) -> (fileName: String, fileExtension: String) { 
    // Break the NSURL path into its components and create a new array with those components. 
    let fileURLParts = fileURL.path!.components(separatedBy: "/") 

    // Get the file name from the last position of the array above. 
    let fileName = fileURLParts.last 

    // Break the file name into its components based on the period symbol ("."). 
    let filenameParts = fileName?.components(separatedBy: ".") 

    // Return a tuple. 
    return (filenameParts![0], filenameParts![1]) --> Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 
} 

致命錯誤:超出範圍的索引 我做了什麼錯?

+0

檢查您的節數。也許你正試圖設置比你的網址中存在的數據高的行數。 – Amit

+0

@Amit是你提到的那個嗎? FUNC的tableView(_的tableView:UITableView的,numberOfRowsInSection段中:int) - >詮釋{ 回報fileURLs.count } – JameS

+0

是的,這是方法...與放置斷點cellforRowAt_indexpath再次運行代碼。並檢查你的代碼崩潰的迭代。 – Amit

回答

1

非常明確的錯誤。您正嘗試訪問NSURL的數組fileUrls以外的索引。 用你的代碼,我看到一個可能的問題導致這種錯誤。如你所知,你在代碼的開頭初始化一個空數組。然後,在您的private func prepareFileURLS()中,通過在您的NSURLS中添加此語句fileURLs.append(csvFile as NSURL)來填充陣列。問題是你真的完成了你的陣列嗎?您的代碼是否通過了您的if語句if FileManager.default.fileExists(atPath: csvFile.path)我鼓勵你打印你的fileURLs數組,看看它包含了什麼和他的長度。

然後您的isssue將在您的private func extractAndBreakFilenameInComponents(fileURL: NSURL) -> (fileName: String, fileExtension: String)中傳播,並使用此語句return (filenameParts![0], filenameParts![1])。由於您的初始數組fileURLs不包含任何內容,所以您未使用感嘆號filenameParts進行解包,並且沒有值(= nil)導致致命錯誤。

+0

謝謝!這正是我所尋找的。是的,直到用戶在應用程序中創建文件之後,數組仍然是空的。這可能聽起來很愚蠢,但我怎樣才能返回帶有可選值的文件路徑,因爲在開始時不會有任何文件。 @ Arrabidas92 – JameS

+0

使它成爲可選的?在前面 – Arrabidas92

相關問題