0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · 课时

属性与实例变量

理解属性与实例变量之间的区别,以及如何使用它们在对象中存储数据。

属性与实例变量 是 CoddyKit 上的免费 Objective-C iOS Development for Legacy & Enterprise Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

常见问题解答

「属性与实例变量」课时是免费的吗?

是的 — 「属性与实例变量」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Objective-C iOS Development for Legacy & Enterprise Apps 课程的其余内容,请升级到 CoddyKit PRO。 Objective-C iOS Development for Legacy & Enterprise Apps 课程共包含 4 节课。

「属性与实例变量」这节课中我会学到什么?

理解属性与实例变量之间的区别,以及如何使用它们在对象中存储数据。 你通过在浏览器中直接运行的动手代码来练习 Objective-C iOS Development for Legacy & Enterprise Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Objective-C iOS Development for Legacy & Enterprise Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Objective-C iOS Development for Legacy & Enterprise Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「属性与实例变量」课时需要多长时间?

大多数 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