Study Notes, study notes cover

Source: Internet
Author: User

Study Notes, study notes cover
I. What do I need to pay attention to when using NSTimer?

1. Make sure there is an active RunLoop.
NSTimer is a timing mechanism based on RunLoop, which involves the knowledge extension of the default main thread and sub-thread RunLoop, and the knowledge point to prevent timer failure when the page slides:
Solution: [[nsunloop currentRunLoop] addTimer: timer forMode: nsunloopcommonmodes];

2. nst creation and revocation must be performed in the same thread and cannot be performed across threads.

3. Risks of Memory leakage
When NSTimer is used, timer keeps a strong reference to the target and userInfo parameters. The target and userInfo of nstdate will be released only when the invalidate method of NSTimer is obtained. If the repeats parameter is NO in the timer generation method, the invalidate method is automatically called after the timer is triggered. If the repeats parameter is YES, you must manually call the invalidate method to release the strong reference of timer to target and userIfo.

Funny. I have also written a blog called "Implementation of timer NSTimer> GCD", which talks about the points worth attention when using NSTimer and how to avoid using GCD. During the interview on the same day, it may be that the previous question about runtime was not answered well, which caused mood fluctuations and affected the use of this question. Of course, I must also face up to myself who are not familiar with the knowledge point and need to study and consolidate it.
My blog about this article Portal: http://www.cnblogs.com/beckwang0912/p/7027484.html

 

Ii. How does _ weak automatically set the object value to nil?

In Objective-C advanced programming, Chapter 1.4 describes the _ weak modifier in detail. I have read this book a long time ago and remember that an internal implementation is a hash table on that day.

Here, the reference book briefly describes the implementation:

{     id __weak obj_weak = obj;}

Assume that the variable obj is appended with the _ strong modifier and the object is assigned a value.
Compiler simulation code:

id obj_weak;obj_weak = 0;objc_storeWeak(&obj_weak,obj);objc_storeWeak(&obj,0);

From the above, we can clearly see what the key and value are, respectively. The key is the memory address of the object obj, and the value is the memory address of the obj_weak. This can also explain how multiple weak pointers point to the same assignment address and solve the problem of setting all nil. The table structure is similar to the following:
Bytes
The nil process is as follows:
1. Obtain the record with the obsolete object address as the key value from the weak table
2. assign a value of nil to all addresses with the _ weak modifier variable in the record.
3. delete records from the weak table
4. Delete the address of the obsolete object from the reference counter table as a key value record

At that time, I asked why nil should be set? My answer is to prevent wild pointers. Now I guess according to the structure of the _ weak hash table, it should be feasible to prevent the wild pointer, because if the variable reference object using the _ weak modifier is discarded, if this variable is not set to nil, the pointer is directed to a non-existent address. If it is assigned another value or used, crash may occur.

 

3. What if removeObserver is not paired with addObserver during Notification usage?

I did not answer this question at the time. I did pay attention to this question during my work. I also checked the engineering code when I came back, some other colleagues forgot to remove it, but the program never crashed. This made me very curious, is it because Apple's ARC automatically removed the registration notification when the page pops out of the stack? Otherwise, a message or program crash will be sent to the wild pointer object. I tried to write a demo specially. The main idea is:

1. register the notification in UIViewController without removing it.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];

Remove comment:

- (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    //[[NSNotificationCenter defaultCenter] removeObserver:self name:@"test" object:nil];}

2. Navigate to this page and pop it out. Finally, click the send notification button event.

TestViewController *vc = [[TestViewController alloc] init];[self.navigationController pushViewController:vc animated:YES];

Click after pop:

- (void)clickBtn:(id)sender{    [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];}

I found that nothing happened after clicking the button. The logs () I prepared in advance were not printed and the program did not crash.

-(Void) test {NSLog (@ "current thread = % @", [NSThread currentThread]); NSLog (@ "Notification call ");}

This further validates my conjecture that when the UIViewController is destroyed, it quietly helped me remove it. With this idea, I will further verify it. My idea is that I only need to prove that the removeObserver method of nsicationicationcenter is called when pop comes out.

# Import "nsicationicationcenter + RemoveTest. h "@ implementation nsicationcenter Center (RemoveTest)-(void) removeObserver :( id) observer {NSLog (@" ====%@ test whether to remove notification ==== ", [observer class]);} @ end

Follow the steps above and try again. The magic happened.

10:33:31. 610 beck. wang [1366: 116266] ===__ NSObserver test whether to remove notification ===10:33:31. 675 beck. wang [1366: 116266] ==== ViewController test whether to remove notification ===10:34:52. 939 beck. wang [1366: 116266] === TestViewController test whether to remove notification ===

The above inference is correct. When the UIViewController is destroyed by itself, it quietly helped me to remove it.

However, I recommend registration and removal to avoid unexpected situations. Apple also recommends this. I think the reason why Apple recommends registration and removal in pairs may be to reregister the same notification in a way that is not conducive to performance and memory. In addition, let's think about such a scenario, if the registered notification is not removed, and the post object receives the message has been released, whether the message is sent to a non-existing object, is unknown crash occurring in the program? This is to be verified by me.

 

Iv. reuse mechanism of UITableViewCell

Principle: UITableView creates a UITableViewCell with only one screen (or more than one screen), and the others are retrieved and reused. Every time the Cell slides out of the screen, it will be placed into a set (OR array) (this is equivalent to a reuse pool). to display a Cell at a certain position, it is first retrieved from the set (OR array). If yes, it is directly displayed. If no, it is created. The benefits of doing so can be imagined, greatly reducing the memory overhead.

At that time, I asked how the "reuse pool" was designed? After receiving the prompt, I replied that the dictionary is used for storage, the key is the passed-In identifier, and the value is UITableViewCell. After that, I checked the information and found only the following materials: NSMutableArray * visiableCells and NSMutableDictnery * reusableTableCells IN THE UITableView header file. In visiableCells, save the currently displayed cells, and reusableTableCells save reusable cells. This so-called "reuse pool" should be a variable dictionary set [NSMutableDictnery * reusableTableCells]. The key is the passed-In identifier, and the value may be an array used to store UITableViewCell.

 

5. Calling a function from OC is called sending messages. Why does apple design Runtime? What are the benefits of designing it?

I did not answer this question well. After I come back, I will check the materials. Here I will talk about my ignorance.

1. The biggest feature of runtime is the message forwarding mechanism.

The Design of message distribution allows Objective-C to include classes of objects during compilation. In C ++, We can customize the "class" based on the method called template. OC unifies the base class such as NSObject (not only NSObject, but also various root protocols) add a definition for all classes. You can send messages to any object including NULL pointer nil. The message distribution mechanism makes it easier to implement interventions or hook the original target (methods, variables, etc.) during runtime without re-compiling, and has more practical application value.

2. runtime is the implementer of the OC Memory Management Model

Objective-C's memory management principle is simply a "reference counting" mechanism. If a module needs to reference an object, it will add 1 to the reference count value for object statistics and record it in the structure information of the object, when the module no longer needs this object, it minus 1. When the reference count of this object is 0, it can be considered that this object is no longer needed, timely destroy and release memory (Recycle resources ).

3. Runtime allows us to use standard interfaces (C functions)Queries and dynamically extends all Objective-C class variables, methods, attributes, and protocols.To enrich the language and class library features of the project.

The following figure illustrates how to use runtime:

References:

Ten Runtime usage

Why is Runtime like this?

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.