首先,您無法寫入任何內容mainBundle。爲了給您寫信給plist,您需要將其複製到文檔目錄中。這是這樣做的:
- (void)createEditableCopyOfIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"];
success = [fileManager fileExistsAtPath:writablePath];
if (success)
return;
// The writable file does not exist, so copy from the bundle to the appropriate location.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Template.plist"];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);
}
所以調用此函數將檢查文件是否存在於文檔目錄中。如果它沒有將文件複製到文檔目錄。如果文件存在,它只是返回。接下來,您只需訪問該文件即可讀取和寫入該文件。要訪問您只需要文檔目錄的路徑並將您的文件名添加爲路徑組件。
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"Template.plist"];
從plist中獲取數據:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
將文件寫入迴文件目錄。
[array writeToFile:filePath atomically: YES];
沒有成功仍然獲得數組的空值,我已經添加了你的方法 - (void)createEditableCopyOfIfNeeded,然後從視圖DidLoad調用它作爲[self createEditableCopyOfIfNeeded],調用此函數後,我已經使用你的代碼讀取plist文件但得到空值 – 2012-02-09 09:35:49
我曾遇到過這個問題。你可能需要做的是重置模擬器。這段代碼所做的是,如果有一個名爲Template.plist的文件,它將不會覆蓋它。所以如果文件已經存在,那麼這個代碼將不會爲你工作,直到你刪除它。通過運行模擬器並點擊iOS模擬器菜單並按下重置內容和設置,即可完成此操作。這將擦拭模擬器清潔。其他選項是使用NSLog(@「%@」,filePath);然後按照路徑直到找到文件並將其刪除。 – Jaybit 2012-02-09 15:59:03