取代舊的對象,我用Objective-C編程新手,我得到了我的NSMutableArray一個問題...NSMutableArray裏總是最後一個
當我做出的第一次嘗試,我的數據都是很好保存,但如果我想進行第二次嘗試,第一次被新的覆蓋,新的也被保存。
個例理解:
第一次嘗試:
Tabobjets : (
{
Contact = 1;
DateARendre = 1;
DateJour = "2013-03-19 19:27:29 +0000";
Nom = 1;
Rendu = 0;
Titre = 1;
}
)
第二次嘗試:
Tabobjets : (
{
Contact = 2;
DateARendre = 2;
DateJour = "2013-03-19 19:27:40 +0000";
Nom = 2;
Rendu = 0;
Titre = 2;
},
{
Contact = 2;
DateARendre = 2;
DateJour = "2013-03-19 19:27:40 +0000";
Nom = 2;
Rendu = 0;
Titre = 2;
}
)
這裏是我的代碼
@interface SecondViewController() {
NSMutableDictionary *tabObjet;
NSMutableArray *tabObjets;
NSString *appFile;
}
@end
@implementation SecondViewController
- (void)viewWillAppear:(BOOL)animated{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
appFile = [documentsDirectory stringByAppendingPathComponent:@"Bigre.plist"];
if (tabObjets == nil) {
tabObjets = [[NSMutableArray alloc] initWithContentsOfFile:appFile];
}
if (tabObjet == nil) {
tabObjet = [[NSMutableDictionary alloc] init];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saisieReturn :(id)sender{
[sender resignFirstResponder];
NSLog(@"Tabobjet avant : %@",tabObjet);
NSLog(@"Tabobjets avant : %@",tabObjets);
//inscription dans un dictionnaire
[tabObjet setObject:_titreObjet.text forKey:@"Titre"];
[tabObjet setObject:_nomPersonne.text forKey:@"Nom"];
[tabObjet setObject:_infoContact.text forKey:@"Contact"];
[tabObjet setObject:[NSDate date] forKey:@"DateJour"];
[tabObjet setObject:_dateARendre.text forKey:@"DateARendre"];
[tabObjet setObject:[NSNumber numberWithBool:NO] forKey:@"Rendu"];
int numItems = [tabObjets count];
[tabObjets insertObject:tabObjet atIndex:numItems];
NSLog(@"Tabobjet apres : %@",tabObjet);
NSLog(@"Tabobjets apres : %@",tabObjets);
//écriture dans un fichier plist
[tabObjets writeToFile:appFile atomically:YES];
}
@end
非常感謝您的幫助:)
請詳細說明問題。而且,僅供參考,TabObjets是一個可變數組,而不是字典,因此其行爲如預期。我錯過了什麼? – Monolo 2013-03-19 19:47:34
對不起,但我不是英文^^,並得到了一些問題要非常明確。 如你所說,如果我的數據被NSMutableArray覆蓋是正常的? – Glou94 2013-03-19 19:53:44
是的,這是正常的。在第一次運行中,您添加一個對象並保存該數組。在第二次運行中,您用第一個對象讀取數組,添加一個新數組,這樣該數組就有兩個項目。然後你保存它。它應該是。 – Monolo 2013-03-19 19:57:09