2011-11-06 26 views
0

我有一個對象具有自定義UIViews,UIImage,和一些字符串的NSMutableArray。iOS的文件編碼/解碼視圖和圖像文件目錄

我把那個對象放到字典裏。字典被推入NSData然後我這樣做:

NSString *path; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
path = [paths objectAtIndex:0]; 

NSString *fileName = DATA; 
path = [path stringByAppendingPathComponent:fileName]; 

NSMutableData *data = [[NSMutableData alloc]init]; 
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; 
[archiver encodeObject:dict forKey: DATA]; 
[archiver finishEncoding]; 

[[NSFileManager defaultManager] createFileAtPath:path 
             contents:data 
             attributes:nil]; 

它保存成功。當我嘗試加載數據時,文件系統顯示我的對象已保存,但是當我嘗試解碼時,它說我的數據爲空。

這裏是我的解碼碼:

-(NSDictionary*)loadData 
{ 
NSString *path; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
path = [paths objectAtIndex:0]; 
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL]; 

if (directoryContent != nil && [directoryContent count] > 0) 
{ 
    NSLog(@"CONTENT COUNT: %d",[directoryContent count]); 
    NSString *fileName = DATA; 
    path = [path stringByAppendingPathComponent:fileName]; 
    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]]; 
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 
    NSDictionary *dict = [unarchiver decodeObjectForKey: DATA]; 
    [unarchiver finishDecoding]; 

    return dict; 
} 
else 
    return nil; 
} 

我的應用程序,用戶可以四處移動一堆意見,我只是試圖找到一個簡單的方法來存儲視圖幀,而無需提取轉換每個int /字符串值。我也希望不必將我的UIImage分解成一個字節數組,然後將其重新加載回UIImage。

我在這裏做瘋狂的東西,希望功能是不可能的?

我唯一的選擇是將數組中的每個UIView細分爲轉換,幀等單獨的值嗎?

想法?

+1

你真的想存檔視圖並寫出UIImages嗎?關於你要完成的任務,你不會詳細討論,但如果你只是允許用戶移動視圖並且想保留這些視圖的位置,那麼更好的方法是歸檔這些視圖的位置,然後用這個位置信息重新創建視圖? – mattyohe

+0

我可以做到這一點。那麼UIImage呢?我確實需要存儲此圖像並重新加載它。我怎麼做? – spentak

回答

2

文檔目錄是否包含您的數據文件以外的任何內容? (我認爲它總是至少包含一個名爲「收件箱」的子目錄)。我注意到在您的loadData方法,這些行:

path = [path stringByAppendingPathComponent:fileName]; 
    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]]; 

您可以附加fileNamepath,但你不使用它。您只需從directoryContent中提到的第一個文件中讀取。

相關問題