2011-11-03 63 views
3

我想保存/寫入一個數組到文檔目錄,我完全卡住了。我已經在線查看了多個源代碼。我從NSArray切換到NSMutableArray,並沒有奏效。從我可以告訴的是文件沒有被寫入,因爲測試返回null。在此先感謝寫一個NSArray到文件

NSArray *results = [parser objectWithData:data1]; 

NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:results]; 
// Create a dictionary from the JSON string 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"EmployeeData.plist"]; 

//NSLog(@"the path is %@, the array is %@", path, array2); 

/////write to file///// 
[array2 writeToFile:path atomically:YES]; 

NSMutableArray *test = [[NSMutableArray alloc ]initWithContentsOfFile:path]; 

NSLog(@"the test is %@", test); 

**更新**

我添加幾行代碼

BOOL write = [results writeToFile:path atomically:YES]; 

NSLog(@"did it right? %@", write); 

,並寫爲空,這是什麼意思?

這是我的數組

{ 
    0 = "<null>"; 
    1 = "John Doe"; 
    10 = 512; 
    11 = "<null>"; 
    12 = 1; 
    13 = 1; 
    2 = Doe; 
    3 = Jon; 
    4 = "<null>"; 
    5 = johndoe; 
    6 = "<null>"; 
    7 = "<null>"; 
    8 = "[email protected]"; 
    9 = "<null>"; 
    Type = 1; 
    Active = 1; 
    Depart = "<null>"; 
    Emp = "<null>"; 
    Ext = "<null>"; 
    FirstName = Jim; 
    Fl = 512; 
    Name = "John Doe"; 
    Log = jd; 
    Mobile = "<null>"; 
    Title = "<null>"; 
} 

的衆多對象中的一個執行空值有什麼關係呢?

已解決!

我意識到空值可能會導致一些問題,所以我改變了我的查詢來照顧它,並立即保存。上面的代碼是100%正確的,它的工作原理!

感謝您的幫助

+1

你可以欺騙並寫入'[array2 description]'到文件中。 –

回答

16

按照該documentationwriteToFile:只適用,如果你的數組的內容僅限於類型(NSStringNSDataNSArray,或者NSDictionary對象)了一把。如果您的數組中有任何其他類型的對象,那麼它將不會正確寫入文件(或根本不寫入)。

還要注意writeToFile:返回一個布爾值,指示操作是否成功。

如果你的數組包含不兼容的類型,你將不得不考慮使用類似NSKeyedArchiver的東西來序列化你的數據。

+0

我擁有的是一個解析網站的數組。我從JSON獲得了數組中的信息。所以它是一個對象數組。你認爲這與它無關嗎? – zach

+0

是的,可能有些對象是不兼容的類型。你可以非常簡單地通過執行如下操作來檢查:'for(NSObject * obj in array){NSLog(「%@」,[obj class]); }'。請注意,如果您有複雜的JSON數據結構,那麼您可能需要修改循環以通過嵌套數組和字典進行遞歸。 – aroth

+0

我剛剛在上面的描述中添加了我的一個對象 – zach