2012-11-25 3 views
2

이제 iOS 개발을위한 Objective C 학습을 시작했습니다.Objective C에서 변수를 초기화하기 전에 변수를 0으로 설정하는 것이 중요합니다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"BirdSightingCell"; 

    static NSDateFormatter *formatter = nil; 
    if (formatter == nil) { 
     formatter = [[NSDateFormatter alloc] init]; 
     [formatter setDateStyle:NSDateFormatterMediumStyle]; 
    } 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    BirdSighting *sightingAtIndex = [self.dataController objectInListAtIndex:indexPath.row]; 
    [[cell textLabel] setText:sightingAtIndex.name]; 
    [[cell detailTextLabel] setText:[formatter stringFromDate:(NSDate *)sightingAtIndex.date]]; 
    return cell; 
} 

질문 1 : 변수 CellIdentifier 및 포맷터를 선언하면서

은 "정적"는 무엇을합니까 나는 다음과 같은 코드를 이해하려고 노력 중이 야? 내가 정적으로 선언하지 않는다면 여전히 작동하므로 정적을 사용하면 어떤 이점이 있습니까?

Q2 :

static NSDateFormatter *formatter = nil; 
if (formatter == nil) { 

항상이 표현은 사실이 아닙니까? 왜 우리는 그 진술을 거기에서 사용합니까?

+1

정적 변수이므로 메서드가 실행될 때만 nil이 처음으로 설정됩니다. 처음으로 변수가 nil인지 확인한 후 해당 변수를 만들고 이후 호출에서 포맷터는 정적이므로 일단 작성되면 해당 변수는 메소드 내에 만 존재하지만 범위가 제한됩니다. http://en.wikipedia.org/wiki/Static_variable을 참조하십시오. – Sandeep

답변

2

static은이 방법을 여러 번 호출 할 때 "공유 된"변수라는 것을 의미합니다. 처음 호출되면 정적 변수는 nil이됩니다. 다음 번에는 그것이 마지막 전화 도중 무엇으로 설정 되었습니까?

2

static은 프로그램 시작시 변수를 nil으로 설정하고 해당 명령문을 실행할 때마다가 아니라 여러 함수 호출에서 해당 값을 유지한다는 것을 의미합니다.

처음 함수를 호출하면 nil이되고 if 문은 실행됩니다. 함수에 대한 후속 호출은 if 문에있는 코드가 다시 실행되지 않도록 비 nil 값으로 설정합니다.

이것을 초기화 지연이라고합니다.

관련 문제