0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · 강의

속성과 인스턴스 변수

속성과 인스턴스 변수의 차이를 이해하고 객체 내부에 데이터를 저장하는 방법을 익힙니다.

속성과 인스턴스 변수은(는) CoddyKit의 무료 Objective-C iOS Development for Legacy & Enterprise Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Objective-C iOS Development for Legacy & Enterprise Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Data in Your Objects

When you create objects in Objective-C, they often need to store information. Think of a Person object needing to store a name and an age.

This data is stored using either instance variables or properties. Both hold data, but they offer different levels of control and safety.

Instance Variables (IVars)

Instance variables (often called ivars) are variables declared directly within a class's interface or implementation block. They hold the actual data for an object.

  • They are like direct storage slots inside your object.
  • You can access them directly from within the object's methods.
  • Direct access from outside the object is generally discouraged for good object-oriented practice.

Declaring an Instance Variable

You declare instance variables within the @interface block, typically inside curly braces {}. By default, they are @protected.

Try running this simple example:

#import <Foundation/Foundation.h>

@interface MyObject : NSObject {
    // This is an instance variable
    int myValue;
}
- (void)printValue;
@end

@implementation MyObject
- (void)printValue {
    NSLog(@"My value is: %d", myValue);
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MyObject *obj = [[MyObject alloc] init];
        obj->myValue = 10; // Direct access (usually avoided externally)
        [obj printValue];
    }
    return 0;
}

Introducing Properties (`@property`)

While ivars store data, properties provide a controlled way to access that data. A property declaration automatically generates getter and setter methods.

  • Getter: A method to retrieve the value (e.g., name).
  • Setter: A method to change the value (e.g., setName:).

This is crucial for encapsulation and managing how data is read and written.

Declaring a Property

You declare properties using the @property directive in the @interface block. This tells the compiler to prepare accessor methods.

For example, @property (assign) int age; declares an age property.

#import <Foundation/Foundation.h>

@interface Person : NSObject
// Declare a property for name and age
@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) int age;

- (void)introduce;
@end

@implementation Person
// @synthesize name = _name; // Not strictly needed in modern Objective-C
// @synthesize age = _age;   // The compiler synthesizes automatically

- (void)introduce {
    NSLog(@"Hello, my name is %@ and I am %d years old.", self.name, self.age);
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] init];
        person.name = @"Alice"; // Using dot syntax (setter)
        person.age = 30;       // Using dot syntax (setter)
        [person introduce];    // Accessing via getter inside method
    }
    return 0;
}

Property Attributes: Memory

Properties can have attributes that influence how their accessor methods are generated, especially concerning memory management (though full ARC is covered later).

  • strong (default for objects): Keeps a strong reference, preventing the object from being deallocated.
  • weak: Creates a weak reference, allowing the object to be deallocated if no strong references exist. Prevents retain cycles.
  • assign (default for primitives): Used for non-object types (int, float, structs). Simply assigns the value.
  • copy: Creates a copy of the object rather than retaining the original. Useful for mutable objects like NSString to prevent external modification.

Property Attributes: Atomicity

Another important attribute is related to thread safety:

  • atomic (default): Ensures that the getter and setter methods are thread-safe. This means a complete value is always returned or set, even if multiple threads try to access it simultaneously.
  • nonatomic: Does not guarantee thread safety for accessors. This is faster and often used when you manage thread safety manually or don't need it for a specific property.

For most iOS development, nonatomic is preferred for performance, unless specific thread safety is required for that property.

Dot Syntax vs. Message Syntax

Properties allow you to use dot syntax (e.g., object.name) which is a convenient shortcut for calling the getter and setter methods.

  • object.name is equivalent to [object name] (getter).
  • object.name = @"Bob"; is equivalent to [object setName:@"Bob"] (setter).

Both are valid, but dot syntax is often used for properties to improve readability.

#import <Foundation/Foundation.h>

@interface Car : NSObject
@property (strong, nonatomic) NSString *model;
@property (assign, nonatomic) int year;
@end

@implementation Car
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Car *myCar = [[Car alloc] init];
        
        // Using dot syntax to set values
        myCar.model = @"Tesla Model 3";
        myCar.year = 2023;
        
        // Using dot syntax to get values
        NSString *carModel = myCar.model;
        int carYear = myCar.year;
        
        NSLog(@"Car: %@, Year: %d", carModel, carYear);
        
        // Equivalent message syntax for setting
        [myCar setModel:@"Ford F-150"];
        [myCar setYear:2020];
        
        // Equivalent message syntax for getting
        NSString *newModel = [myCar model];
        int newYear = [myCar year];
        
        NSLog(@"New Car: %@, Year: %d", newModel, newYear);
    }
    return 0;
}

IVars vs. Properties: When to Use?

Generally, you should use properties for almost all data storage that needs to be accessed from outside the object, or even consistently within the object.

  • Use properties for public (or even private) access to data, leveraging their accessor methods and attributes.
  • Use raw instance variables (ivars) only if you need to store data that should never be accessed directly, even by subclasses, or for very specific performance optimizations where you absolutely don't want accessor overhead (rare).

Modern Objective-C with ARC heavily favors properties.

Property Quick Check

Consider the following Objective-C property declaration:

@property (nonatomic, copy) NSString *productName;

Which of the following statements is TRUE about this property?

Recap: IVars & Properties

We've explored how Objective-C objects store data using instance variables and properties.

  • Instance variables (ivars) are direct storage locations within an object.
  • Properties provide controlled access to data via generated getter/setter methods.
  • Key property attributes like strong, weak, assign, copy manage memory.
  • atomic and nonatomic control thread safety for accessor methods.
  • Dot syntax is a convenient way to access properties, translating to method calls.
  • Properties are the preferred way to manage object data in modern Objective-C.

자주 묻는 질문

“속성과 인스턴스 변수” 강의는 무료인가요?

네 — “속성과 인스턴스 변수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Objective-C iOS Development for Legacy & Enterprise Apps 강의 전체를 잠금 해제할 수 있습니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“속성과 인스턴스 변수”에서 뭘 배우나요?

속성과 인스턴스 변수의 차이를 이해하고 객체 내부에 데이터를 저장하는 방법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Objective-C iOS Development for Legacy & Enterprise Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Objective-C iOS Development for Legacy & Enterprise Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Objective-C iOS Development for Legacy & Enterprise Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“속성과 인스턴스 변수” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Objective-C iOS Development for Legacy & Enterprise Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 클래스, 객체 및 메서드
  2. 속성과 인스턴스 변수
  3. 프로토콜과 카테고리
  4. 상속과 메서드 재정의
← Objective-C iOS Development for Legacy & Enterprise Apps(으)로 돌아가기