title: Mo Kong Interview Notes 1
date: 2016-02-23 09:02
tags: Technology#
Mo Kong Interview Notes 1#
I went for an interview at B station in the afternoon and was asked a question about memory management. They asked many questions, but this one left a deep impression on me because I couldn't answer it well. It was really frustrating. (I was filled with tears)
On the way back, my phone ran out of battery, and then I remembered this. I thought to myself, "Oh my, I think I know what this is." And then I thought some more, and I indeed knew. And then I thought about what I said at that time, and I just wanted to be quiet.
Let's look at the question, just understand it, don't worry about the wrong format, it's roughly like this
@AutoreleasePool {
A = [[A alloc] init];
B = [[B alloc] init];
A.b = B;
B.a = A;
}
Then they asked, does this cause a circular reference? Which step causes it? Can you explain it to me?
And then I explained it poorly, the interviewer couldn't stand it and asked how to fix it so that there won't be a circular reference?
And then I said something bad again.
Now that I think about it, why did I say that at that time? It seems like I was scared. The interviewer said, imagine I'm someone who hasn't learned Objective-C and only knows C, and explain it to me; and then I thought it was a difficult question, so I got excited...
Sigh, I'm filled with tears, let's not talk about it, let's look at the answer I came up with on the way back.
First, it does cause a circular reference, that's for sure. And then which step? It's the last step, if there's no last step, there won't be a circular reference.
- A = [[A alloc] init]
This step creates an A object, A's reference count is 1. - B = [[B alloc] init]
This step creates a B object, B's reference count is 1. - A.b = B
This step makes A hold B, B's reference count increases by 1; because A holds B, in order to release B, A needs to release the held B first. - B.a = A
This step makes B hold A, A's reference count increases by 1; similarly, because B holds A, in order to release A, B needs to release the held A first.
And then this causes a circular reference.
Finally, how to fix it and make them release normally? It's simpler, because the circular reference is caused by the last step, so we can change the last step. Because B holds A and causes the circular reference, we can just not let B hold A, use __weak... weak reference, the reference count won't increase.
@AutoreleasePool {
A = [[A alloc] init];
B = [[B alloc] init];
A.b = B;
__weak weakB = B;
weakB.a = A;
}