이제 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) {
항상이 표현은 사실이 아닙니까? 왜 우리는 그 진술을 거기에서 사용합니까?
정적 변수이므로 메서드가 실행될 때만 nil이 처음으로 설정됩니다. 처음으로 변수가 nil인지 확인한 후 해당 변수를 만들고 이후 호출에서 포맷터는 정적이므로 일단 작성되면 해당 변수는 메소드 내에 만 존재하지만 범위가 제한됩니다. http://en.wikipedia.org/wiki/Static_variable을 참조하십시오. – Sandeep