Program Tip

Objective-C에서 nil, NIL 및 null의 차이점

programtip 2020. 10. 31. 10:03
반응형

Objective-C에서 nil, NIL 및 null의 차이점


nil, NIL의 차이점을 알고 싶습니다 null. 나는 주위를 훑어 보았고 이것을 발견했습니다.

nil -> Objective-C 객체에 대한 널 포인터

NIL -> Objective-C 클래스에 대한 널 포인터

null -> 원시 유형 또는 데이터 부재에 대한 널 포인터

하지만 "Objective-C 객체"와 "클래스"라는 용어를 명확하게 이해할 수 없습니다.

제게 설명해주세요. 또한, 같은 단어가 NSNullNSNil오브젝티브 C의는? 그렇다면 그것이 무엇인지 설명하십시오.


nilid통해 선언 된 추상 유형 또는 Objective-C 유형에 해당하는 Objective-C 개체의 리터럴 null 값입니다 @interface. 예를 들면 :

NSString *someString = nil;
NSURL *someURL = nil;
id someObject = nil;

if (anotherObject == nil) // do something

Nil유형에 해당하는 Objective-C 클래스의 리터럴 null 값입니다 Class. 대부분의 코드는 클래스를 참조하는 데 변수가 필요하지 않기 때문에 일반적으로 사용되지 않습니다. 한 가지 예는 다음과 같습니다.

Class someClass = Nil;
Class anotherClass = [NSString class];

NULL임의의 C 포인터에 대한 리터럴 널값입니다. 예를 들어

int *pointerToInt = NULL;
char *pointerToChar = NULL;
struct TreeNode *rootNode = NULL;

NSNullnull을 나타내는 개체의 클래스입니다. 사실, 하나의 객체, 즉 +[NSNull null]. 이는 리터럴 null 값 nil이기 때문에 nil, 즉 객체가 아니기 때문에 다릅니다 . 반면에의 단일 인스턴스 NSNull는 적절한 객체입니다.

NSNullnil값을 저장할 수 없기 때문에 Foundation 컬렉션에서 자주 사용 됩니다. 딕셔너리의 경우 주어진 키가 딕셔너리에 해당 객체가 없음을 나타 내기 위해 -objectForKey:반환 nil됩니다. 즉, 키가 딕셔너리에 추가되지 않았습니다. 특정 키가 있지만 아직 값이 없음을 명시하고 싶다면 [NSNull null].

예를 들어, 다음은 사전이 nil값을 저장할 수 없기 때문에 예외를 발생시킵니다 .

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:nil forKey:@"someKey"];

반면에 다음 코드는 객체 [NSNull null]가 아니므로 유효 nil합니다.

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNull null] forKey:@"someKey"];

Foundation 컬렉션에는 nil목록의 요소 수를 지정하지 않고도 개체 목록의 끝을 나타내는 마커로 사용 하는 이니셜 라이저가 있다는 점을 언급 할 가치가 있습니다 . 이것은 nilFoundation 컬렉션에 저장할 수 없기 때문에 발생할 수 있습니다. 예를 들어

NSArray *array = [NSArray arrayWithObjects:@"one", @"two", nil];

에 관해서 NILNSNil, 오브젝티브 C 또는 Apple 재단에서 그런 일이 없습니다.


나는 확실하지 오전하지만 난 생각 nil만 대신에 사용한다 idJava 및 C ++ 프로그래머가 같은 생각 될지, pointerobject. 사용 NULL되지 않은 객체 포인터에 대해.

nil일반적으로 Objective-C 객체 유형에 NULL사용되는 반면 c 스타일 포인터에 사용됩니다.


Nil, Null 및 nil은 아래와 같이 사용됩니다.

1> Objective c 클래스의 경우 Nil

2> Objective c 객체의 경우 nil

3> C 포인터의 경우 Null

예:

1> 클래스 A = 무;

2> NSString strName = nil;

3> char * pointerChar = NULL;


클래스가 있다고 가정하면 인스턴스를 null 값 ( Java에서 와 동일)으로 초기화하려는 경우 MyClass규칙 nil에 따라 사용됩니다.null

MyClass *obj = nil;


null 값에 대한 기본 포인터를 초기화하려면 (c에서와 동일) 다음을 사용하십시오.

int *ptr = NULL; 


Classnull 값 ( nullJava에서 와 동일) 참조 하도록 초기화하려면 다음을 사용하십시오.

Class classRefOfMyClass = Nil;

그것은 단지 관례 일뿐입니다. 그렇지 않으면 Nil 또는 nil은 동일한 의미를 가지며 아마도 NULL, nil 또는 Nil 모두 동일합니다.

다음은 objc.h파일 에있는 이들에 대한 정의입니다.

#ifndef Nil
# if __has_feature(cxx_nullptr)
#   define Nil nullptr
# else
#   define Nil __DARWIN_NULL
# endif
#endif

#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif

그리고 stddef.h

#define NULL ((void*)0)

그리고 __DARWIN_NULLin 의 정의_types.h

#define __DARWIN_NULL ((void *)0)

So there is no difference logically. The main idea here is to initialize a pointer whether C or Objective-C to 0. If you have knowledge of C then you can assign

int *ptr = 0;

without type casting 0 to a pointer. As you don't need to typecast 0 to assign it to a pointer.

In short they all are 0 and nothing else.


This will help you to understand the difference between nil,NIL and null.

All three of these values represent null, or zero pointer, values. The difference is that while NULL represents zero for any pointer, nil is specific to objects (e.g., id) and Nil is specific to class pointers. It should be considered a best practice of sorts to use the right null object in the right circumstance for documentation purposes, even though there is nothing stopping someone from mixing and matching as they go along.

The below link may help you in some way:

http://nshipster.com/nil/

Here is some important part from the link:

enter image description here


nil, NIL and null. is depended on your requirement.

NSNull

collections like NSArray and NSDictionary not being able to contain nil values.

NSMutableDictionary *MymutableDictionary = [NSMutableDictionary dictionary];
MymutableDictionary[@"someKey"] = [NSNull null]; // Sets value of NSNull singleton for "someKey"
NSLog(@"Keys: %@", [mutableDictionary allKeys]);

nil

all pointers that object has to other objects begin as nil, so it's unnecessary to, for instance, set self.(association) = nil in init methods.

In other languages, like C++, this would crash your program, but in Objective-C, invoking a method on nil returns a zero value.

if (name != nil)
{
........
}

Symbol Value Meaning

nil (id)0 literal null value for Objective-C objects

Nil (Class)0 literal null value for Objective-C classes

참고URL : https://stackoverflow.com/questions/5908936/difference-between-nil-nil-and-null-in-objective-c

반응형