Objective-C에서 nil 테스트 — if (x! = nil) 대 if (x)
인터넷에서 찾은 대부분의 예는 다음과 같습니다.
if(x != nil)
// ...
이것에 문제가 있습니까?
if(x)
// ...
간단한 프로그램에서 두 가지를 모두 시도했지만 차이점을 찾을 수 없었습니다.
오브젝티브 C에서는 nil
라는 값으로 정의되고 __DARWIN_NULL
본질적으로 평가, 0
또는 false
IF-제표. 그러므로 쓰기 if (x == nil)
는 쓰기 if (!x)
와 if (x != nil)
같고 쓰기 는 같다 if (x)
(비교 false
는 부정 을 생성하고 비교 true
는 조건을 동일하게 유지하기 때문에).
어느 쪽이든 코드를 작성할 수 있으며, 어느 쪽이 더 읽기 쉽다고 생각하는지에 따라 다릅니다. 내가 찾아 if (x)
더 이해하려고하지만, 당신의 스타일에 따라 달라집니다.
비교하는 if (someCondition == true)
것과 같습니다 if (someCondition)
.
그것은 모두 당신과 누가 코드를 읽을 것인지에 달려 있습니다.
편집 : Yuji가 올바르게 언급했듯이 Objective-C는 C의 상위 집합이므로 0이 아닌 값으로 평가되는 모든 조건은 true로 간주되므로 someCondition
위의 예에서 정수 값으로 평가하는 경우 예를 들어, -1과 비교하면 true
결과가 false
되며 if 문은 평가되지 않습니다. 알아야 할 것.
양자 모두
if (x != nil)
과
if ( x )
동등하므로 귀하의 의견에 따라 귀하의 코드를 더 쉽게 읽을 수 있는 변형을 선택하십시오 (및 귀하의 코드를 읽고 지원할 다른 사람).
nil을
확인하는 가장 안전하고 안전한 방법은 Make a common method, and add all these null :
+ (NSString *)trimWhiteSpaceAndNewLine:(NSString *)string {
NSString *stringSource = [NSString stringWithFormat:@"%@",string];
if ([stringSource isEqualToString:@"(null)"]) {
stringSource = @"";
return stringSource;
}
if ([stringSource isEqualToString:@"<null>"]) {
stringSource = @"";
return stringSource;
}
if ([stringSource isEqualToString:@"<nil>"]) {
stringSource = @"";
return stringSource;
}
if ([stringSource isKindOfClass:[NSNull class]]) {
stringSource = @"";
return stringSource;
}
if ([stringSource isEqualToString:@""]) {
stringSource = @"";
return stringSource;
}
if (stringSource == nil) {
stringSource = @"";
return stringSource;
}
NSString *stringFinal = [stringSource stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return stringFinal;
}
And check
NSString *strUuid = [Common trimWhiteSpaceAndNewLine:[dict valueForKeyPath:@"detail.uuid"]];
if (![strUuid isEqualToString:@""]) {
// do your stuff
}
Both are the same and this is a style question and it boils down to whether you prefer:
if (something) { ... }
versus
- if (something != nothing) { ... }
I have always found #1 more clear but #2 is used extensively in documentation and hence the field so it is better to both know both forms and adapt to what a project uses and be stylistically consistent.
if([yourNullObject isKindOfClass:[NSNull class]]){
//if it is null
}else{
//if it is not null
}
참고URL : https://stackoverflow.com/questions/6177719/testing-for-nil-in-objective-c-ifx-nil-vs-ifx
'Development Tip' 카테고리의 다른 글
BackgroundWorker의 처리되지 않은 예외 (0) | 2020.10.29 |
---|---|
들어오는 모든 http 요청을 어떻게 모니터링합니까? (0) | 2020.10.29 |
Angular JS의 행에 대체 클래스를 할당하는 방법은 무엇입니까? (0) | 2020.10.29 |
Gulp로 여러 파일을 복사하고 폴더 구조를 유지하는 방법 (0) | 2020.10.29 |
mail () 함수에 대한 오류 메시지를 어떻게 얻을 수 있습니까? (0) | 2020.10.29 |