2011-10-12 2 views
1

방금 ​​Objective C 및 xcode로 시작합니다. 나는 NSUserdefaults를 탐험 해왔다.plist에 데이터가 없을 때 else 문이 생기는 경우 - NSUserdefaults

텍스트 필드의 입력을 plist 파일에 저장할 수 있습니다. Nad는 응용 프로그램이 다시 시작될 때 레이블로 다시 검색 할 수 있습니다.

내가 할 수없는 것은 plist 키가 비어있는 경우 표시 할 대안 텍스트를 얻는 것입니다. 아래 코드를 사용하면 텍스트 필드를 통해 텍스트를 plist에 다시 추가 할 때까지 내 레이블이 비어 있습니다. 제발 포인터주세요.

if (theNewString.length > 0) { 
    [mylabel setText:theNewString]; 
} else { 
    [mylabel setText:@"nothing stored"]; 
} 

답변

3

. 이 작업을 수행하는 가장 좋은 방법은 인스턴스가 생성되기 전에 호출 get's 객체의 + 초기화 방법을 사용하는 것입니다

+ (void)initialize{ 
    // This method may be called more than once when it is subclassed, but it doesn´t matter if user defaults are registered more than once. 

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    // Add each initial value to a dictionary 
    NSDictionary *appDefaults = [NSDictionary 
     dictionaryWithObject:@"nothing stored" forKey:@"textFieldKey"]; 

    // Then store the dictionary as default values 
    [defaults registerDefaults:appDefaults]; 
} 

좋은 프로그래밍 규칙은 입력 오류를 방지하기 위해 키를 정의 할 수도 있습니다 :

#define HSTextFieldKey @"textFieldKey" 
0
if (theNewString != nil) { 
     [mylabel setText:theNewString]; 
    } else { 
     [mylabel setText:@"nothing stored"]; 
    } 
+0

안녕하세요. 고마워요. 그것은 작동하지 않는 것 같습니다. 어쩌면 viewwillappear에서 이것을 사용하는 데 문제가 있습니까? – Dave

0

NSUserDefaults위한 적절한 방법은 디폴트 값으로 초기화한다 : nil의 문자열 인 경우에는 0 (빈) 길이의 유효한 문자열 처리

- (void)viewWillAppear:(BOOL)animated; 
{ 
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults]; 
    NSString *theNewString=[ud objectForKey:@"textFieldKey"]; 
    // update the label 
    if (theNewString) { 
     [mylabel setText:theNewString]; 
    } else { 
     [mylabel setText:@"nothing stored"]; 
    } 
} 
관련 문제