티스토리 뷰

Objective-C 문법에서 왜 항상 변수 앞에 *로 선언하나 궁금했었는데..

 

NSString *someString = @"The string";

This syntax, mostly lifted straight from C, declares a variable called someString whose type is NSString*. This means that it is a pointer to an NSString. All Objective-C objects must be declared in this way because the memory for objects is always allocated in heap space and never on the stack. It is illegal to declare a stack-allocated Objective-C object.

 

-> Objective-C 에서 객체는 메모리 주소인 포인터로 참조된다.

 

cf. 인스턴스는 Heap 영역, 주소값은 Stack에 있음

 

이렇게

 

 

Q. 근데 원래 문법이 이런건지 아니면 어떤 이유가 있는건지..?

그런데 생각해보면

NSMutableArray *array = [[NSMutableArray alloc] init];

Objective-C 에선 이렇게

항상 객체(Object) 인스턴스를 선언하면 거기에 alloc 으로 개발자가 직접 메모리를 할당시켜 주는 과정이 필요한데

메모리 할당은 당연히 주소에 해야하니까 처음부터 포인터로 선언하는게 맞음

 

 

+ 그래서

nonobjective type인 int, float, double, char 등은 선언할 때 * 안 쓰고, 그냥 stack 공간 쓰일 수 있음!

 

 

 


https://www.oreilly.com/library/view/effective-objective-c-20/9780133386950/

 

Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS and OS X Programs

Write Truly Great iOS and OS X Code with Objective-C 2.0! Effective Objective-C 2.0 will help you harness all of Objective-C’s expressive power to write OS X or iOS code … - Selection from Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS

www.oreilly.com

 

이 책으로 공부 중이고, 기억하면 좋을 것 같은 부분을 발췌 + 공부 + 정리합니다.

 

 

'Objective-C 2.0' 카테고리의 다른 글

5. Memory Management  (0) 2022.05.10
4. Protocols and Categories  (0) 2022.03.04
3. Interface and API Design  (0) 2022.01.25
2. Objects, Messaging, and the Runtime  (0) 2022.01.19
1. Accustoming Yourself to Objective-C  (0) 2022.01.17
댓글