SoFunction
Updated on 2025-04-12

The difference between @property and Ivar in the basics of iOS

@property

Attributes are actually an encapsulation of member variables. Let's first understand it this way:

@property = Ivar + setter + getter

Ivar

Ivar can be understood as a variable in a class, and its main function is to save data.

Let’s take a look at an example. The following examples can clearly explain these two things:

We create a new Person class

@interface Person : NSObject
{
NSString *name0;
}
@property(nonatomic,copy)NSString *name1;
@end
@implementation Person
- (instancetype)init {
if (self = [super init]) {
}
return self;
}
@end

In this Person name0 is the member variable and name1 is the attribute.

Let's create a Person:

Person *p= [[Person alloc] init];
p.name1 = @"abc";
NSLog(@"%@",p.name1);

We will find that I cannot access name0 outside the Person class. What does this mean? This means that the member variable <font color=red>name0</font> can only be accessed inside its own class.

Therefore, we infer that @property actually also has interface properties, that is, it can be accessed by external objects.

p.name1 = @"abc";

This line of code actually calls the setter method of name1 in Person.

NSLog(@"%@",p.name1);

This line of code actually calls the getter method of name1 in Person.

Let’s talk about the setter and getter methods. Everyone should know that OC has strict naming specifications. Take this example as an example, it is automatically generated based on name1.

- (void)setName1:(NSString *)name1{}
- (NSString *)name1

Note: The situation of MRC is not discussed here, and all explanations are subject to ARC.

@synthesize

This keyword is used to specify member variables

In Person's implementation, we changed the code to this:

@implementation Person
@synthesize name1 = _name2;
- (instancetype)init {
if (self = [super init]) {
_name2 = @"aaa";
}
return self;
}
@end

In this way, we specify that the member variable of name1 is _name2, and we cannot type the attribute _name1 in Person's initialization init method.

Person *p= [[Person alloc] init];
// p.name1 = @"abc";
NSLog(@"%@",p.name1);

We comment out the line of assignment and we can see that the print result is: aaa.

The above is the difference between @property and Ivar, the basic knowledge of iOS introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!