What can happen to 2 pieces of code? What’s the difference?
- Global concurrent queue loop 1000 asynchronous tasks set name,1000 May set self.name at the same time.
- The result is an error in the first paragraph and no problem in the second.
- The only difference between these two pieces of code is the length of the string. Why is that?
- What exactly is this NSTaggedPointer
- First look at the nature of the operation of the set method under MRC
@property (strong, nonatomic) NSString *name; - (void)setName:(NSString *)name { if (_name ! = name) { [_name release]; _name = [name retain]; } } @property (copy, nonatomic) NSString *name; - (void)setName:(NSString *)name { if (_name ! = name) { [_name release]; _name = [name copy]; }}Copy the code
- 1. Check whether they are consistent
- 2. The reference count is reduced by one to release the old member variable
- 3. Assign the reference count to +1.
- So the thread might call Release multiple times. Bad memory access.
- Solution 1 is atomic
- Solution 2 Unlock the device.
Tagged Pointer
- Starting from 64-bit, iOS introduces Tagged Pointer technology to optimize storage of small objects such as NSNumber, NSDate, and NSString
- Before Tagged Pointer is used, objects such as NSNumber need to dynamically allocate memory and maintain reference counting. The NSNumber Pointer stores the address value of the NSNumber object in the heap
- After using Tagged Pointer, the Data stored in the NSNumber Pointer becomes Tag + Data, that is, the Data is stored directly in the Pointer
- When Pointers are insufficient to store data, dynamically allocated memory is used to store data
- Objc_msgSend can recognize Tagged Pointer, such as the intValue method of NSNumber, and directly extract data from Pointer, saving previous call overhead
- How do I check whether a Pointer is Tagged Pointer?
- IOS platform, the highest significant bit is 1 (64bit)
- Mac platform, the least significant bit is 1
- TaggedPointer (used when a string is small) places data directly into a pointer.
- For example, this NSNumber is stored in a pointer.
- Let’s verify the NSNumber
- @4 = 0x427 4 is real data. 27 is a tag, indicating that the data is of the NSNumber type. On the MAC platform, the data type is 7 = 0B0111, and the least significant bit is 1.
- Ios is the highest bit in the example above
- B = 0b1011 most significant bit is 1 so it is taggedPointer