The difference between @ES1en and Ivar

  • 2020-06-23 02:00:06
  • OfStack

@property

A property is a wrapper around a member variable. Let's think about it this way:

@property = Ivar + setter + getter

Ivar

Ivar can be understood as a variable in the class, which is mainly used to store data.

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

Let's 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 CASE, name0 is the member variable and name1 is the attribute.

We created an Person:


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

We'll see that I can't access name0 outside of the Person class. What does that mean? This indicates the member variable < font color=red > name0 < /font > Can only be accessed within its own class.

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


p.name1 = @"abc";

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


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

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

Say again the setter and getter methods. As you probably know, oc has strict naming conventions. In this case, name1 is automatically generated


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

Note: the case of MRC is not discussed here. The premise of all 1-cut explanations is under ARC.

@synthesize

This keyword is used to specify member variables

In our implementation of Person, we changed the code to look like this:


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

In this way, we specify the member variable of name1 as _name2. We cannot type the attribute _name1 in the initializing init method of Person.


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

We comment out the assigned line and see that the print is: aaa.


Related articles: