2014-10-10 87 views
2

我有一個iOS遊戲,我試圖將設置(通常存儲在一個數組中)保存到文件中。測試以查看文件是否已存在

目前,我已打開文件,並在openStack處理程序中讀取;我有在關機處理程序中寫入的文件...

但在openStack處理程序中,如何測試以查看該文件是否已實際創建...並且如果它不存在,我想創建一個和寫在一些默認設置

這樣做的最佳方式是什麼?

回答

0

通常情況下,我只需打開並閱讀該文件。接下來,我將內容放入變量中。如果內容恰好爲空,那麼我使用默認值。這使得不必檢查文件是否存在,更重要的是,它與未來版本的軟件更兼容。

on readPrefs 
    put specialFolderpath("documents") & "/prefs.dat" into myPath 
    put url ("binfile:" & myPath) into myPrefs 
    // here, the result may contain "can't open file" 
    put line 1 of myPrefs into gHighscore 
    if gHighScore is empty then put 0 into gHighscore 
    put line 2 of myPrefs into gLicenseKey 
    if gLicenseKey is empty then put "unregistered" into gLicenseKey 
end readPrefs 

你也可以檢查該文件,並使用一個略有不同的腳本:

on readPrefs 
    put specialFolderpath("documents") & "/prefs.dat" into myPath 
    if there is a file myPath then 
    put url ("binfile:" & myPath) into myPrefs 
    put line 1 of myPrefs into gHighscore 
    put line 2 of myPrefs into gLicenseKey 
    end if 
    if gHighScore is empty then put 0 into gHighscore 
    if gLicenseKey is empty then put "unregistered" into gLicenseKey 
end readPrefs 

更多的變化是可能的,例如如果文件無法打開,您可以檢查結果並設置默認值。

0

您可以檢查文件是否已經存在,如果它不存在,您可以將默認值放入文件中,然後創建該文件。 見下面

if there is not a file "mysettings.dat" 
then put myDefaultsettings into URL "binfile:mysettings.dat" 
相關問題