2009-12-18 5 views
0

안녕하세요. 나는 처음으로 소비자가 그것을 사용하는 모달을 표시하는 응용 프로그램에 노력하고 있습니다. 저장 버튼을 누르면 요청한 정보를 저장할 .plist 파일이 있습니다. 나는 .plist 파일을 잘 읽을 수 있고 save 메소드를 실행하면 잘 작동하지만 .plist 파일은 업데이트되지 않습니다. 나는이 문제에 대해 그렇게 확신하지 못한다. 나는이 모달을 보여줍니다.iPhone 앱이 .plist 파일에 값을 저장하지 않습니다.

- (void) getConsumerInfo { 
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"consumer.plist"]; 
NSMutableDictionary *plistConsumerInfo = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 

NSString *hasAppeared = [plistConsumerInfo objectForKey:@"HasAppeared"]; 

if(hasAppeared != kHasAppeared) { 
    ConsumerInfoViewController *tmpConsumerInfoVC = [[ConsumerInfoViewController alloc] 
       initWithNibName:@"ConsumerInfoView" bundle:nil]; 
    self.consumerInfoViewController = tmpConsumerInfoVC; 
    [self presentModalViewController:consumerInfoViewController animated:YES]; 
    [tmpConsumerInfoVC release]; 
} 
} 

앱이 시작될 때 첫 번째보기 전화에서 viewDidLoad 메서드에 의해 호출됩니다. consumerInfoViewController 내에서 데이터가 입력 된 텍스트 필드가 있고 Save 버튼을 누르면이 메서드가 호출됩니다.

- (IBAction)saveConsumerInfo:(id)sender { 
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"consumer.plist"]; 
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 

NSString *tmpDiversName = txtDiversName.text; 
NSString *tmpLicenseType = txtLicenseType.text; 
NSString *tmpLicenseNum = txtLicenseNumber.text; 
NSString *tmpHasAppeared = @"1"; 
NSString *tmpNumJumps = @"3"; 

[plistDict setValue:[[NSString alloc] initWithFormat:@"%@", tmpDiversName] forKey:@"ConsumerName"]; 
[plistDict setValue:[[NSString alloc] initWithFormat:@"%@", tmpLicenseType] forKey:@"LicenseType"]; 
[plistDict setValue:[[NSString alloc] initWithFormat:@"%@", tmpLicenseNum] forKey:@"LicenseNumb"]; 
[plistDict setValue:[[NSString alloc] initWithFormat:@"%@", tmpNumJumps] forKey:@"NumJumps"]; 
[plistDict setValue:[[NSString alloc] initWithFormat:@"%d", tmpHasAppeared] forKey:@"Show"]; 
[plistDict writeToFile:filePath atomically: YES]; 
NSLog([[NSString alloc] initWithContentsOfFile:filePath]); 
[self dismissModalViewControllerAnimated:YES]; 
} 

이 모든 것이 딸꾹질이없이 정상적으로 실행되지만 파일은 업데이트되지 않습니다. 업데이트를 통해 앱 전체에서이 정보를 사용하고 플래그를 업데이트하여 데이터가 입력 된 후에 다시 표시되지 않도록 할 수 있습니다. 더 이상 필요한 정보가 있으면 알려주십시오. 미리 감사드립니다!

답변

2

번들 디렉토리에 쓸 수 없습니다.

대신 캐시 폴더 또는 문서 폴더를 사용하십시오. NSSearchPathForDirectoriesInDomains 또는 NSHomeDirectory 함수의 반환 값을 수정하여 이러한 폴더의 위치를 ​​찾는 방법에 대한 정보는 iPhone 설명서를 참조하십시오.

+0

굉장! 그게 전부지만 또 다른 문제가있는 것 같아. 나는 가서 파일 시스템의 plist 파일을 살펴볼 수 있으며 그 값은 존재하지만 2 개의 더 많은 값 키 쌍을 생성 한 것으로 보인다. 기묘한. 리소스 폴더로 가져온 plist 파일을 사용하고 싶습니다. 나는 그걸 알아 내야 할 것 같아. 답변 해주셔서 감사합니다! – Trent

+1

만약 나 였다면, 캐시 * 또는 도큐멘트 폴더의 plist 파일을 앱이 * 완전히 성공적으로 * 시작한 적이없는 플래그로 사용하고 응용 프로그램 후에 캐시/문서에 plist 파일 만 만들면됩니다. 및/또는 사용자 *가 최초의 첫 번째 앱 실행 워크 플로를 성공적으로 완료합니다. – martinr

0

그냥이에 추가, 당신은 시뮬레이터에서 번들에 쓸 수없는 경우에도 할 수없는 장치에 - 나 시뮬레이터와 장치 사이의 시간 디버깅의 힙을 받았 느니라 원인이 뭔가

0

이것이 누구에게나 유용하다면, 이것은 비슷한 것을하기 위해 사용하는 코드입니다. I use it 새 버전이 보증 된 경우 마지막 버전보다 크면 일부 샘플 문서를 처음 실행하거나 선택적으로 (주석 처리 된 섹션) 복사 할 수 있습니다.

BOOL firstrun() 
{ 
    CFStringRef firstRunKey = CFSTR("lastVersion"); 

    CFNumberFormatterRef formatter; 

    CFStringRef currentVersionString; 
    CFMutableStringRef currentVersionMutableString; 
    CFNumberRef currentVersion; 

    CFStringRef lastVersionRunString; 
// CFMutableStringRef lastVersionRunMutableString; 
// CFNumberRef lastVersionRun; 



    currentVersionString = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey); 
    currentVersionMutableString = CFStringCreateMutableCopy(NULL, 0, currentVersionString); 
    CFStringFindAndReplace(currentVersionMutableString, CFSTR("."), CFSTR(""), CFRangeMake(0, CFStringGetLength(currentVersionString)), 0); 
    formatter = CFNumberFormatterCreate(NULL, NULL, kCFNumberFormatterNoStyle); 
    currentVersion = CFNumberFormatterCreateNumberFromString(NULL, formatter, currentVersionMutableString, NULL, kCFNumberFormatterParseIntegersOnly); 

    lastVersionRunString = CFPreferencesCopyAppValue(firstRunKey, kCFPreferencesCurrentApplication); 

    if (lastVersionRunString == NULL) 
    { 
     // first run 
     NSFileManager *f = [NSFileManager defaultManager]; 
     NSBundle *b = [NSBundle mainBundle]; 
     NSError *e; 

     NSArray *xs = [NSArray arrayWithObjects: @"Welcome", 
           @"A Child's Garden of Verses", 
            @"Address to a Haggis", 
               @"Sonnet 18", nil]; 

     for (id x in xs) 
     { 
      BOOL s = [f copyItemAtPath: [b pathForResource: x ofType: @"txt"] 
        toPath: [DocumentManager pathForDocumentWithName: x] 
        error: &e]; 

      if (s == YES) 
      { 
       NSLog(@"Copied first run file %@ successfully.", x); 
      } 
      else { 
       NSLog(@"Failed to copy %@.", x); 
      } 
     } 
    } // else { 
     // The following is to enable support for new releases needing to show new information 
/* 
     lastVersionRunMutableString = CFStringCreateMutableCopy(NULL, 0, lastVersionRunString); 
     CFStringFindAndReplace(lastVersionRunMutableString, 
           CFSTR("."), 
           CFSTR(""), 
           CFRangeMake(0, CFStringGetLength(lastVersionRunMutableString)), 
           0); 
     lastVersionRun = CFNumberFormatterCreateNumberFromString(NULL, formatter, lastVersionRunMutableString, NULL, kCFNumberFormatterParseIntegersOnly); 

     CFComparisonResult cr = CFNumberCompare(lastVersionRun, currentVersion, NULL); 
*/  

// } 

    // Update last run version 
    CFPreferencesSetAppValue(firstRunKey, currentVersionString, kCFPreferencesCurrentApplication); 
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); 

    CFRelease(currentVersionMutableString); 
    CFRelease(formatter); 
    CFRelease(currentVersion); 

    return (lastVersionRunString == NULL); 

    } 
관련 문제