Добавление 3 значений к списку динамически, а затем перезаписывает одно за другим, если добавлено больше - PullRequest
1 голос
/ 08 августа 2011

Я использую plist в своем приложении, я могу добавить значения в plist и все работает нормально. Но мне нужно только 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];  

}

1 Ответ

2 голосов
/ 08 августа 2011

Вам нужно будет сохранить переменную, в которой хранится индекс, в который был вставлен последний элемент (lastInsertionIndex below). Предполагается, что в plist в данный момент есть 3 элемента, а 4-й элемент вставляется (lastInsertionIndex = 2), код должен выглядеть следующим образом:что-то вроде -

// 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,

Акшай

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...