Note in the ARC environment:

1. In the class

@ Property nature:

@property = ivar(instance variable) + getter/setter method declaration + getter/setter method implementation;Copy the code

When you declare a property using @property in a class, whether in a.h or a.m, the compiler automatically generates an underlined instance variable + a declaration of the corresponding getter/setter method + an implementation of the corresponding getter/setter method;

Such as:

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;

@end
Copy the code

By default, a member variable named _name is added to the.h of the Person class, setName and name: declarations of two methods (getters/setters), such as:

@interface Person : NSObject
{
    NSString *_name;
}
- (void)setName:(NSString *)name;
- (NSString *)name;

@end
Copy the code

And add setName and name: implementations of the two methods (set/get) to the.m of the Person class, as in:

- (void)setName:(NSString *)name{
    _name = name;
}
- (NSString *)name{
    return _name;
}
Copy the code

2. In the classification

@ Property nature:

@property = getter/setter method declaration;Copy the code

You can see that when we declare properties using @Property in a classification, we only generate declarations of getter/setter methods, and we do not automatically generate implementations of ivAR (instance variables) and getter/setter methods.

Such as:

@interface Person (test)

@property (nonatomic, copy) NSString *name;

@end
Copy the code

At this point, only setName and name: declarations for two methods (set/get) are automatically generated in the classified. H, as in:

@interface Person (test)

- (void)setName:(NSString *)name;
- (NSString *)name;

@end
Copy the code

Also, in.m there will be a hint:

Prompt that you need to provide an implementation of setter/getter methods;

If no implementation of setter/getter methods is provided, an unrecognized selector is reported as follows:

Therefore, we usually add attributes to the classification indirectly by adding associated objects through the Runtime. As follows:

#import "Person+test.h"
#import <objc/runtime.h>

@implementation Person (test)

- (NSString *)name {
    return objc_getAssociatedObject(self, @selector(name));
}
- (void)setName:(NSString *)name {
    objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
Copy the code

The specific realization principle of classification (Category) is not explained in detail here.