Analysis (002) iOS properties

Today simply looked oc attributes and modifiers, of course, there are some simple strength and other references, it is named property.

List what some simple attributes and modifiers.

static int countNum = 1;

@protocol LJLDelegate <NSObject>
-(void)showDelegate;
@end

typedef void(^LJLBlock)(int);

@interface LJLPropertyViewController ()

@property(nonatomic, assign) int num;
@property(nonatomic, assign) double height;
@property(nonatomic, assign) int age;
@property(nonatomic, strong) NSString * str;
@property(nonatomic, copy) NSString * str2;
@property(nonatomic, weak) id <LJLDelegate>delegate;
@property(nonatomic, copy) LJLBlock block;
@property(nonatomic, strong) UIButton * button;
@property(nonatomic, assign, readwrite) BOOL circular;//允许读写

@end

Attribute created by the above manner, where the system automatically creates a set / get method of
operating a real machine, the arm64. Calling a method front objc_msgSend will first prepare the required parameters id self, SEL, value
   

self.num = 10;
self.height = 1.85;
self.age = 30;
self.str = @"ljl";


 Register is used to store parameters, typically 0x0 ~ 0x7
 parameter register is stored at this time
 0x0: Self ID
 0x1: setNum:
 0x2: 10
    
strong retain and release operation carried out automatically at the bottom. Then it will use a modified copy distinguish atoms and non-atomic.
 1, non-original property (nonatomic)

In the underlying implementation

oldValue = *slot
*slot = newValue;


 2, atomic (Atomic)

spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
oldValue = *slot;
*slot = newValue;        
slotlock.unlock();

Lock, then
 oldValue = slot *
 * slot = newValue;
 unlock
 this lock can only guarantee the safety set / get the
 

self.str = @"ljl123";

Create an object the size of memory needed to open up
 to create a minimum amount of memory for the object 16.
Reference: https://www.bilibili.com/video/av79839999?from=search&seid=7187104079046109220
 create a class that inherits from NSObject, then success is also an object (class object), the object and the structure of the memory right, this place question. First record about the details come later found more explanation, such as the god who in turn guide the wing:

@interface LGPerson : NSObject
@property(nonatomic, assign) int num;
@property(nonatomic, assign) double height;
@property(nonatomic, assign) int age;
@end
    
LGPerson *p1 = [LGPerson alloc];
p1.age = 10;
p1.num = 5;
p1.height = 1.8;

(lldb) x/4gx p1
0x600000a899a0: 0x0000000109a79b00 0x0000000a00000005
0x600000a899b0: 0x3ffccccccccccccd 0x0000000000000000

Except this time the first 8 bits ISA (first attribute of the object is isa, hidden attributes) than
int is four 8-bit double. This time the second eight put int num, does not fit the remaining four double height, it will put the third eight. Next is placed behind int int the second 8 bits. As the code 0x0000000a00000005. 10 and 5. This contains the value of our set. This place is a memory optimization system, the back of the second place four points to the value of num 5. But with the combination of the following to say, then I do not quite understand this does not seem in line with the principle of memory alignment, so there are doubts with ready answers to find the answer, first record.
 

@implementation LJLPropertyViewController

struct StructTwo {
    double b;       //8字节  0-7
    int c;          //4字节  8-12  后面补齐 13-15  总大小为16
} MyStruct3;

struct StructTwo1 {
    double b;       //8字节  0-7
    int c;          //4字节  8-12  后面补齐 13-15
    double f;       //8字节  16-23
    int e;          //4字节  24-28  后面补齐 29-31  总大小为32
} MyStruct2;

NSLog(@"%lu---%lu", sizeof(MyStruct3), sizeof(MyStruct2));
16  32

However, by the above structure MyStruct3 (16) MyStruct2 (32) to verify seen, the memory footprint for the structure of the row, in this order. Memory size occupied by the attribute determining its position based on fact (e.g. in MyStruct2, bc from 0 0-7, c 8 starts from 8-11, f 16-23,11 and 16 starts from a position after the previous 16 fit f so filled.)

 MRC manual memory management
    delegate use ASSIGN
 ARC automatic memory management
    delegate use weak
 

Modifiers

. 1, strong (retain substantially the same effect)
    strong reference
    is the default modifier modifier
    holding the object, the reference count of +1. Modified objects are destroyed in the reference count is zero.
 2, weak
    weak references
    reference count does not increase (the equivalent of a new pointer to the original object, the original object when released will be released), the reference count of the object is 0, while the object of the release address pointer is set nil. Generally used to break the cycle of references and modified delegate.
 3, assign
    weak reference
    basic data types and the type is generally used to modify id
    when modified object. When the object's reference count is 0, the object is released it does not set nil pointer, the pointer field occurs. So generally can not modify objects using y assign.
    Because the basic data types typically allocated on the stack, the stack memory is handled automatically by the system, does not cause the pointer field, it is possible to assign a modification.
 4, copy
    the strong reference
    copy modified objects are immutable.
    The equivalent of a copy at the time of call set methods of an object.

@property (nonatomic, copy) NSArray *datas;
NSMutableArray *datas = [NSMutableArray arrayWithObject:@"data"];
self.datas = datas
//相当于 self.datas = [datas copy];

So even if you modify the number of objects inside the datas in the back, it will not affect the number of objects self.datas inside.
 
 5, atomic
    atomicity
    default property
    to ensure the security set / get, but can not guarantee thread safety. And the performance is slower than nonatomic nearly 20 times.
    When the underlying execution system set / get method will lock, thus ensuring that the set / get the time to be safe, but can not guarantee that the whole object is thread safe.
    Illustration: get the thread A method of running a half, thread B calls set at this time because there are so needed and so locked thread A executed, then the object is to get a intact thread A get.
    But if thread A call to get, while thread B, C thread to call all set. A value that is likely to get be B, before the C set, it may be set after one or more of.
 6, nonatomic
    allows simultaneous access by multiple threads, thread safety is not guaranteed. High performance, general use nonatomic.
 
 7, readwrite
    allows read and write operations
    by default modifier, the system automatically generates a set / get method.
 8, readonly
    read-only
    system will only generate a get method does not generate a set method.

ACLStudent.h

@interface ACLStudent : NSObject

@property (nonatomic, assign, readonly) NSInteger studentId;
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, copy, readonly) NSString *lastName;
- (instancetype)initWithStudentId:(NSInteger)studentId firstName:(NSString *)firstName lastName:(NSString *)lastName;
@end

--------------------------
ACLStudent.m
@implementation ACLStudent
- (instancetype)initWithStudentId:(NSInteger)studentId firstName:(NSString *)firstName lastName:(NSString *)lastName {
    self = [super init];
    if (self) {
        _studentId = studentId;
        _firstName = [firstName copy];
        _lastName = [lastName copy];
    }
    return self;
}

If the direct call firstNamesetter method student.firstName = @"Qiu", then direct error, suggesting that is not able to declare the property assignment readonly. KVC then use it?

[student setValue:@"Qiu" forKey:NSStringFromSelector(@selector(firstName))];

Found that success can be modified by KVC, Why look at specific or official documents Accessor Search Implementation the Details .

 9, retain
    other NSObject and its subclasses release the old value of the parameter, and then retain the new value.
    Will retain specified in the wake of incoming messages assignment is to retain value. Objective-C objects can only be used (as i increases will retain the reference count of the object, the basic types of objects and Core Foundation no reference count)
the difference between the copy and retain
    , for example, two NSString * a * B and NSString
    copy is a copy a new data to the new memory address, and b point to a different address, but the content is the same.
    retain new objects retain 1, retain the old object does not change. To after another NSString, the same address (to establish a pointer, pointer copy) the object The retain +. 1.
    The retain a pointer is copied, Copy the contents of the copy
reference count
    e.g. a, b points to a same memory, to the memory is provided a reference count, when memory is allocated and assigned to a time reference count is 1, the reference count when a +1 is assigned to b. Wherein when a release, the reference count -1. When the reference count is 0, x representing the memory is not being referenced by any pointer, the system can be directly freed.
10, const
    variable modifier, read-only.
    This means that the parameter can only read, can not modify the content. Who who nearly modification.
    Purpose:
    to facilitate the test questions to quickly find
    large-scale algorithm can quickly find out which module error

    static NSString * const MB_NET_URL_Dev = @"http://";//开发环境地址
    对于不能修改的数据进行修饰

    NSString * a = @"1234";
    NSString * b = @"5678";
    NSString * c = @"90";

   const NSString * p1 = a;
    p1 = b;
    *p1 = c;//错误  指针指向的地方不能修改

    NSString const *  p2 = a;
    p2 = b;
    *p2 = c;//错误  指针指向的地方不能修改

    NSString * const p3 = a;
    p3 = b;//错误 指针本身不能修改
    *p3 = c;

    const NSString * const p4 = a;
    p4 = b;//错误 指针本身不能修改
    *p4 = c;//错误 指针指向的地方不能修改

11, register
    to register.
    It will preferentially modified variable into register, the various operations and operation of such variables, and quickly.
    But the CPU available to users all over the idle register is limited, then if filled or the need to open up space in the common memory.
 12, static
    static DA Tik S
    static variables, not on the stack area, in the data area.
    static action before the local variable, a function of the end value of this variable is not empty, that changed the life of this variable, and know the end of the whole process, and the value of this variable is only defined its function can be used and re-assignment .
 13, extern
    outside de AI X
    extern function can be used to extend the range of action can be extended across the document, provided that the global pass is extended or modified function is not static in the definition.
 

Strong references Weak references

    strong hold strong references and other objects
    weak, assign an object such as a weak reference does not hold

    __strong NSObject *obj1=[[NSObject alloc] init];
    __strong NSObject *obj2=obj1;
    __weak NSObject *obj3=obj1;
    NSLog(@"%@,%@",obj1,obj2,obj3);
    obj1=nil;
    NSLog(@"%@,%@",obj1,obj2,obj3);
    //输出 :
    //<NSObject: 0x7fef53708b80>,<NSObject: 0x7fef53708b80><NSObject: 0x7fef53708b80
    //(null),<NSObject: 0x7fef53708b80>,(null)

strong object retainCount + 1, weak not. Therefore, when the release objc1 objc2 object retainCount-1 = 1. And objc3 retainCount after objc1 release it to 0, and also followed the release of memory, so objc3 is nil.
 
 Application
    When two different objects have a strong reference would cause a circular reference, it will cause the object can not be released while pointing at each other. - circular references
    so we need to get rid of a circular reference, for example, when the agent stated: @property (nonatomic, weak) id <Delegate> delegate ( using assign at MRC)
    using block will result in a circular reference. You must be self hold block, block and hold self

    [self block:^{
        self.value=1;
    }];

    This time we need to hold a weak reference to self, and self holding block, block holds that the weak reference, released after use and will not cause a circular reference. Other lifting behind the circular reference method block when re-analyzed block detail.

    __weak typeof(self) weakself=self;
     [self block:^{
         weakself.value=1;
     }];

However, the following code will not cause a circular reference. But if the nested deeper, then there will be a circular reference.

    [UIView animateWithDuration:0.2 animations:^{
         self.value=1;
     }];

It is causing a circular reference mainly to see whether they hold each other.
    NSTimer will be a strong reference to the current object, such as enabling the current viewController in a NSTimer, if the direct exit pages this time because NSTimer strong reference to the current VC, VC currently can not be released, so it will cause a memory leak. Before first need to exit pages destroy NSTimer. This is similar resolve in another article Analysis NSTimer   in.
    [The invalidate the Timer];
    the Timer = nil;
 

Analysis of the updated content attribute analysis and some not to, as well as the above-mentioned specific modified KVC later. More than a little early for the content of personal profiles and test capacity to learn, and interact more, there are problems but also hope God give you big correction.

Published 83 original articles · won praise 12 · views 180 000 +

Guess you like

Origin blog.csdn.net/shengdaVolleyball/article/details/104698154
Recommended