Propriétés et variables d’instance
Comprenez la différence entre les propriétés et les variables d’instance, et apprenez à les utiliser pour stocker des données dans les objets.
Propriétés et variables d’instance est une leçon Objective-C iOS Development for Legacy & Enterprise Apps gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Objective-C iOS Development for Legacy & Enterprise Apps, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Objective-C iOS Development for Legacy & Enterprise Apps comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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 likeNSStringto 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.nameis 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,copymanage memory. atomicandnonatomiccontrol 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.
Questions Fréquemment Posées
La leçon « Propriétés et variables d’instance » est-elle gratuite ?
Oui — le texte complet de « Propriétés et variables d’instance » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Objective-C iOS Development for Legacy & Enterprise Apps, passe à CoddyKit PRO. Le cours Objective-C iOS Development for Legacy & Enterprise Apps comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Propriétés et variables d’instance » ?
Comprenez la différence entre les propriétés et les variables d’instance, et apprenez à les utiliser pour stocker des données dans les objets. Tu pratiques Objective-C iOS Development for Legacy & Enterprise Apps avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Objective-C iOS Development for Legacy & Enterprise Apps ?
Aucune expérience préalable n'est requise. Objective-C iOS Development for Legacy & Enterprise Apps sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Propriétés et variables d’instance » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Objective-C iOS Development for Legacy & Enterprise Apps ?
Oui. Chaque leçon Objective-C iOS Development for Legacy & Enterprise Apps inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Classes, objets et méthodes
- Propriétés et variables d’instance
- Protocoles et catégories
- Héritage et redéfinition de méthodes