2011-08-08 15 views
1

私のアプリケーションでplistを使用すると、plistの値を追加することができます。plistに3つの値を動的に追加し、さらに1つずつ追加すると1つずつ上書きされます

:ここでの値それはEON、その後の追加にで..one前述の3つの値を上書きしなければならない多くの値を追加しようとした場合 plist、その後に追加する必要があります。..

は、多くのxの値を追加します私のコードです

-(void) myplist :(id) sender { NSLog(@"mylist Clicked"); NSMutableArray *array = [[NSMutableArray alloc] init]; // get paths from root direcory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); // get documents path NSString *documentsPath = [paths objectAtIndex:0]; NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our Data/plist file NSLog(docsDir); NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Data.plist"]; //This copies objects of plist to array if there is one [array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]]; [array addObject:searchLabel.text]; // This writes the array to a plist file. If this file does not already exist, it creates a new one. [array writeToFile:plistPath atomically: TRUE]; 

}

答えて

2

最後の項目が挿入されたインデックスを格納する変数を保持する必要があります(lastInsertionIndex below)。 PLISTと仮定すると、現在第四1が挿入されている& 3つの項目(lastInsertionIndex = 2)、コードがlike-

// get paths from root direcory 

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 

// get documents path 

NSString *documentsPath = [paths objectAtIndex:0]; 

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our Data/plist file 
NSLog(docsDir); 

    NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Data.plist"]; 

    //This copies objects of plist to array if there is one 
    [array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]]; 

//If plist has less than 3 items, insert the new item. Don't use lastInsertionIndex. Else, replace one of the items. 
if([array count] < 3) 
{ 
    [array addObject:[searchLabel.text]]; 
} 
else 
{ 
//Update lastInsertionIndex 
lastInsertionIndex++; 
lastInsertionIndex %= 3; // Max size of array = 3 

[array replaceObjectAtIndex:lastInsertionIndex withObject:[searchLabel.text]]; 
} 

[array writeToFile:plistPath atomically: TRUE]; 

HTH、

になっているはずですAkshay

+0

こんにちはakshayのお返事に感謝を持っています... lastInsertionIndexがどのように宣言されているか教えてください。 – Ranjit

+0

アプリケーションのライフタイムを超えてplistに書き込む必要がある場合は、lastInsertionIndexも保存する必要があります。 NSUserDefaultsを使用して保存できます。あなたの問題を解決するなら、それを答えとして記入してください。 – Akshay

+0

OK、実際にあなたのコードを使用したとき、コンパイラは "宣言されていない識別子lastinsertionindex"というエラーを出しました。..これで何をするのですか。 – Ranjit

関連する問題