2012-06-22 184 views
0

我的應用程序是SplitView類型,我使用UITableView來顯示網站的名稱。在didSelectRowAtIndexPath方法,我使用的代碼行如下::將數據附加到NSDictionary

dateString = [formatter stringFromDate:[NSDate date]]; 
dict = [[NSDictionary alloc] init]; 
dict = [NSDictionary dictionaryWithObjectsAndKeys: urlString, dateString, nil]; 

[history addObject:dict]; 

NSLog(@"dateString: %@", dateString); //will let you know if it's nil or not 
NSLog(@"urlString : %@", [dict objectForKey:dateString]); 

NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
NSLog(@"docDir is yoyo :: %@", docDir); 
NSString *spaceFilePath = [docDir stringByAppendingPathComponent:@"space.txt"]; 
[history writeToFile:spaceFilePath atomically: TRUE]; 

我想要的網站訪問非常久遠的時間戳到NSDictionary「字典」添加URL。我已經在viewDidLoad方法中初始化格式化程序。 History是存儲字典列表的數組。

我用下面的代碼行viewDidLoad方法:

formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

我要追加新址參觀到已存在的文件space.txt名稱。

但是,只有一個名稱出現(上次訪問的網站的網址)。如何將新訪問的siteNames追加到我現有的文件space.txt中?我無法解決這個問題。

感謝和問候。

+0

添加字典之後,打印歷史記錄並驗證值?並且@Rajesh建議檢查您的歷史記錄是否爲零? –

回答

0

你也可以使用你的代碼。請檢查您是否在viewDidLoad中分配了「history」對象。如果沒有,請製作。

+0

好的..大聲笑..分配歷史對象在viewDidLoad工作太!非常感謝 !!這1個單行做了這項工作:: \t「history = [[NSMutableArray alloc] init];」 – gamersoul

+0

但你能否告訴我一些推理的內存分配?我對下面的AliSoftware的說法感到困惑。 – gamersoul

+0

如果你沒有爲一個對象分配內存,並且你正在爲它添加一些值,那麼意味着處理器將保存數據臨時內存,並且每當該範圍完成時它將刪除臨時數據。所以你不能在分配範圍之外使用這些細節。在你的情況下,每次你追加的數據都被保存到臨時內存中,並且在該範圍之後它將刪除添加的數據。這樣每次只保存預設分配的數據。 – Rajesh

0

使用一個NSMutableDictionary(而不是一個NSDictionary)有一個可變的字典(=可以修改)。


附錄: 請注意,您的線路dict = [[NSDictionary alloc] init];是完全無用的,因爲你reaffect在非常下一行的變量「字典」。這就好比如果你這樣做:int a = 5;後面跟着a=8,當然這個變量之前的值被新的值替換,並且之前的值(你的cas中的你的[[NSDictionary alloc] init])丟失了。

+0

kz ..我也嘗試過使用NSMutableDictionary,並刪除了你指定的行。該代碼仍然無法正常工作,即仍然只有最後訪問的網站正在寫入文件space.txt: -/ – gamersoul

0

您正在創建的對象(「字典」)每次都有所不同。意味着你只需在字典中添加選定的細節並寫入。所以你不能看到以前保存的細節。檢查以下代碼以將新訪問的siteNames追加到我現有的文件space.txt中。

dateString = [formatter stringFromDate:[NSDate date]]; 

NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
NSString *spaceFilePath = [docDir stringByAppendingPathComponent:@"space.txt"]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:spaceFilePath]) { 
    NSMutableDictionary *appendDict = [[NSMutableDictionary alloc] initWithContentsOfFile:spaceFilePath]; 
    [appendDict setObject:urlString forKey:dateString]; 
    [appendDict writeToFile:spaceFilePath atomically: TRUE]; 
    [appendDict release]; 
} else { 
    NSMutableDictionary *appendDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:urlString, dateString, nil]; 
    [appendDict writeToFile:spaceFilePath atomically: TRUE]; 
    [appendDict release]; 
} 

我覺得這很有用。

+0

是的..這個解決了!非常感謝:) :) – gamersoul