2011-08-08 2 views
1

plist을 응용 프로그램에 사용하면 plist에 값을 추가 할 수 있으며 필요한 것은 3 개뿐입니다.plist에 3 개의 값을 추가 동적으로 추가하고 추가 할 경우 하나씩 하나씩 겹쳐 쓰기

: 여기

많은 X 값을 추가하는 내 코드입니다 .. 값은 plist에 추가되어야하고, 더 많은 값을 추가하려고하면 그 이후는 지난 3 개 값이 EON 이후의 추가에 의해 ..one 덮어 쓰기한다
-(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를 가정하면 현재 4 하나가 삽입되고 & 3 개 항목이 (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,

하기 Akshay가

+0

안녕하기 Akshay 덕분에 ... lastInsertionIndex가 선언 된 방법을 말해 줄 수 있습니다 .. – Ranjit

+0

응용 프로그램의 수명이 다할 때까지 plist에 작성해야하는 경우 lastInsertionIndex도 저장해야합니다. NSUserDefaults를 사용하여 저장할 수 있습니다. 문제가 해결되면 대답으로 표시하십시오. – Akshay

+0

ok, 실제로 코드를 사용할 때 컴파일러는 "선언되지 않은 식별자 lastinsertionindex."라는 오류를주었습니다. ..이게 무엇을 위해서 ... – Ranjit

관련 문제