0
我有一個資源文件(plist)添加到我的項目。我目前正在編寫某種「助手」來讀取和寫入它。我有3個get和3個set方法。第一個返回頂部的對象,第二個返回另一個字典內部的對象(參見代碼),第三個返回任意給定深度的對象,我只需指定節點名稱即可。 (我希望你能理解我)瀏覽plists和設置對象
問題出在setters上。設置「表面」對象沒有什麼大不了的,所以設置另一個字典中的對象。當我嘗試在一個深度設置一個對象時,問題就出現了。 在我寫任何其他內容之前,我會發布代碼,以便了解我在說什麼。
fullContent是包含文件的NSMutableDictionary
。
//This one is easy, just return the object for the key.
- (id)getSurfaceObjectForKey:(NSString*)key
{
return [fullContent objectForKey:key];
}
//Hope you understand this one. Main parent is a string with the name of the first node. It gets a dictionary out of my plist and returns an object for key (I have a dictionary structured plist)
- (id)getMainParentChildObjectForKey:(NSString*)key
{
NSAssert(!mainParent, @"Main parent must not be nil");
return [[fullContent objectForKey:mainParent] objectForKey:key];
}
//This one gets the element at any given depth I just have to pass in an array containing node names
- (id)getObjectForKey:(NSString *)key atDepthWithChildren:(NSArray *)children
{
id depthElement = fullContent;
for (int i = 0; i < children.count; i++)
depthElement = [depthElement objectForKey:[children objectAtIndex:i]];
return [depthElement objectForKey:key];
}
//Sets a top (surface) object
- (void)setSurfaceObject:(id)object ForKey:(NSString *)key
{
[fullContent setObject:object forKey:key];
[self writePlistContent];
}
//Sets an object inside a dictionary (mainParent - string with the name of dictionary node)
- (void)setMainParentChildObject:(id)object forKey:(NSString *)key
{
[[fullContent objectForKey:mainParent] setObject:object forKey:key];
[self writePlistContent]; //Self explanatory. I write this to file
}
//This is where my problem comes. How do I save this to plist without making any other changes to it? Im guessing I have to rebuild it from inside up?
- (void)setObject:(id)object forKey:(NSString *)key atDepthWithChildren:(NSArray *)children
{
id depthElement = fullContent;
for (int i = 0; i < children.count; i++)
depthElement = [depthElement objectForKey:[children objectAtIndex:i]];
[depthElement setObject:object forKey:key]; //I set the desired object but I dont know how to save it
for (int i = 0; i < children.count - 1; i++)
{
//Here i guess i would have to build the NSDictionary from inside out. Using a NSMutable array perhaps?
}
}
我希望你能理解我的問題。我希望我不要讓事情複雜得太多。我真的很累,現在已經接近24小時,並且不能想出解決這個問題的方法。
預先感謝您。
writePlistContent用'NSMutableDictionary * fullContent'的內容覆蓋整個plist。 – Majster
這不是你想要的嗎? – EarlyRiser
確實如此。但我想用最後一種方法完全改變內容,但我不知道如何。看代碼。 – Majster