1. What is memory leak?
- Memory leaks refers to dynamically allocated memory object has not been in use after system recovery memory, lead to an object holds a memory, always belong to the memory management errors, (such as an object or variable using no release, after the completion of this object has been occupied by memory), a memory leak harm can be ignored, but the memory leak accumulation is very serious, No matter how much memory there is, it will be used up sooner or later
2. What are zombie objects?
- Objects that have been destroyed (objects that can no longer be used) and whose memory has been reclaimed. An object with a reference counter of 0 is released and becomes a zombie object;
3. The wild pointer
- Wild Pointers are also called ‘dangling Pointers’. They occur because the pointer has not been assigned, or the object it points to has been released, such as a zombie object. A wild pointer might point to a piece of junk memory, and sending a message to a wild pointer would crash the program
4. What is a null pointer?
- Unlike a wild pointer, a null pointer is a pointer that does not point to any memory. A null pointer is a valid pointer with a value of
nil,NULL,Nil,0
And so on, sending a message to the null pointer will not report an error, will not respond to the message;
5. OC object memory management mechanism?
- In iOS, reference counting is used to manage the memory of OC objects
- The default reference count of a newly created OC object is 1. When the reference count is reduced to 0, the OC object is destroyed, freeing up its memory
- call
retain
Will make the reference count of the OC object +1, calledrelease
Makes the reference count of the OC object -1
Summary of experience in memory management
- When the alloc, new, copy, and mutableCopy methods return an object, release or autoRelease is called when the object is no longer needed
- To own an object, make its reference count +1; If you don’t want to own an object, let its reference count be -1
You can view automatic pool release using the following private functions
extern void _objc_autoreleasePoolPrint(void);
6. Is there a GC garbage collection mechanism in OC? , GC on iPhone?
- Garbage collection (GC) is a mechanism used in programs to dispose of unused memory objects and prevent memory leaks
- OC itself supports garbage collection, but only on MAC OSX, not iOS
7. Is release or dealloc the opposite of Alloc semantics in OC?
- Alloc is the opposite of dealloc semantics in that alloc is a create variable and dealloc is a release variable
- Retain preserves an object, reference counter +1, and release makes reference counter -1;
8. What is memory overflow?
- When a program is applying for memory, there is not enough memory for it to use. For example, an int is out of memory, but long can store it.
9. Memory area distribution
- In the iOS development process, in order to reasonably allocate limited memory space, the memory area is divided into five areas, which are classified from low address to high address: code area, constant area, global static area, heap, stack.
- Code snippet – binary data generated by program compilation
- Constant area – Stores constant data, usually released automatically by the system when the program is finished
- Global static area — The global area can be divided into uninitialized global area:.bss segment and initialized global area: data segment. Global variables and static variables are stored together. Initialized global variables and static variables are stored in one area. Uninitialized global variables and uninitialized static variables are stored in another area adjacent to the program.
- Heap — Memory that is dynamically allocated during a program’s execution
- Stack — Holds local variables, temporary variables
10. The difference between heap and stack
- According to management
- For the stack, it is managed automatically by the system compiler and does not need to be managed manually by the programmer
- In the case of the heap, the release work is manually managed by the programmer, not timely collection can cause memory leaks
- According to the way of distribution
- The heap allocates and reclaims memory dynamically; there is no statically allocated heap
- Stacks can be allocated in two ways: statically and dynamically
- Static assignment is done by the system compiler, such as assignment of local variables
- Dynamic allocation is allocated by the alloc function, but the stack dynamic allocation is different from the heap, its dynamic allocation is also released by the system compiler, does not need to be manually managed by the programmer
11. How to ensure that multiple developers check for memory leaks?
- Use Analyze for static analysis of code
- To avoid unnecessary complications, use ARC whenever possible for multiplayer development
- Use LEAKS to detect memory leaks
- Use some tripartite tools
12. What is the difference between the use of block in ARC and MRC, and what should I pay attention to?
- For blocks that do not reference external variables, both in ARC and non-ARC, the type is NSGlobalBlock, which can be understood as a global Block without any consideration of scope. Also, Copy or Retain operations on it are invalid
- Use __weak for ARC and __Block for MRC.
How does OC manage the memory solution?
There are three main methods of objective-C memory management: automatic memory management, manual memory management, and automatic release pool.
- Automatic memory counting
- Manual memory count
- Automatic release tank
14. What has ARC done for us?
- LLVM + Runtime will automatically insert retain and release and autorelease into our code without manual management
15. Implementation principle of weak pointer
- The Runtime maintains a weak table that stores all the weak Pointers to an object. The weak table is actually a hash table, where Key is the address of the specified object and Value is an array of addresses of the specified object.
- The Runtime lays out the registered classes and puts weak objects into a hash table. If the reference count of this object is 0, dealloc will be dealloc. If the memory address of the weak object is A, then a will be searched in the weak table, find all the weak objects with a as the key, and set to nil.
16. There are local objects in the method, will it be released immediately after the method?
- If it is a normal local object, it will be released immediately
- If placed in the autoreleasePool autoreleasePool, release at the end of the runloop iteration
17. How to do singleton mode in MRC case
Basic steps to create a singleton design pattern:
- Declare a static instance of a singleton and initialize it to nil.
- Creates a class factory method for a class that generates an instance of that class if and only if the instance of that class is nil
- Implement the NScopying protocol to override the allocWithZone: method to ensure that users do not create another object when they allocate and initialize it directly.
- Override the release, Autorelease, retain, and retainCount methods to ensure the state of the singleton.
- In a multithreaded environment, be careful to use the @synchronized keyword or GCD to ensure that static instances are created and initialized correctly.
18. How do non-OC objects manage memory?
CGImageRelease(ref) is a non-OC object that needs to be released manually. Otherwise, a large number of memory leaks will result in program crash. For others, some objects or variables under CoreFoundation framework need to be released manually, and MALloc in C language code needs to be corresponding to free.
19. CADisplayLink, NSTimer problems, and solutions?
-
CADisplayLink and NSTimer make strong references to target, and if target makes strong references to them, circular references are raised
-
CADisplayLink and NSTimer are implemented based on runloop, which strongly references CADisplayLink and NSTimer. CADisplayLink and NSTimer refer to target again, creating a circular reference
-
Solution 1. Use blocks
// Internally use WeakSelf and turn off timer __weak __typeof(self) WeakSelf = self before the view disappears; NSTimer * timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) { NSLog(@"timer"); }]; self.timer= timer; [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];Copy the code
- Solution 2. Use proxy objects (NSProxy)
@interface MyProxy: NSProxy - (instanceType)initWithObjc:(id)objc; + (instancetype)proxyWithObjc:(id)objc; .m @interface MyProxy() @property(nonatomic,weak) id objc; @end @implementation MyProxy - (instancetype)initWithObjc:(id)objc{ self.objc = objc; return self; } + (instancetype)proxyWithObjc:(id)objc{ return [[self alloc] initWithObjc:objc]; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { return [self.objc methodSignatureForSelector:aSelector]; } - (void)forwardInvocation:(NSInvocation *)invocation { if ([self.objc respondsToSelector:invocation.selector]) { [invocation invokeWithTarget:self.objc]; }}Copy the code
- Usage:
NSTimer * timer = [NSTimer timerWithTimeInterval:1
target:[TimerProxy proxyWithTarget:self]
selector:@selector(test1)
userInfo:nil
repeats:YES];
self.timer = timer;
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Copy the code
20. What is 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
21. Copy is different from mutableCopy
22. How many reasons can memory leaks occur?
- The first possibility: improper use of third-party frameworks;
- Second possibility: block circular reference;
- Third possibility: delegate loop references;
- Fourth possibility: NSTimer circular references
- Fifth possibility: non-OC object memory processing
- Sixth possibility: map-based processing
- Seventh possibility: large number of loop memory inflation
23. What objects under ARC are managed by Autoreleasepool
- When using alloc/new/copy/start mutableCopy method during initialization, generates and hold objects (namely don’t need the pool management, the system will automatically release) to help him in the right position, do not need to manage the pool
- Objects created by normal class methods need to be managed using Autoreleasepool
24. How to implement AutoreleasePool?
AutoreleasePool does not have a structure of its own. It is based on multiple autoreleasepoolpages (a C++ class) as a bidirectional linked list. Push can be used to add objects, POD to eject objects, and release to release objects.
25. Structure of AutoreleasePoolPage? And how to push and pod?
- Calling the push method pushes a POOL_BOUNDARY onto the stack and returns its memory address
- The pop method is called with a POOL_BOUNDARY memory address, and a release message is sent from the last object pushed until the POOL_BOUNDARY is encountered
- Id * next refers to the next area that can hold the address of an AutoRelease object
26. Relationship between Autoreleasepool and Runloop
- The main thread enables Runloop by default. The Runloop automatically creates Autoreleasepool for us and performs Push, Pop, and other operations for memory management
- IOS registers two observers in the Runloop of the main thread
- The first Observer listened
kCFRunLoopEntry
Event will be calledobjc_autoreleasePoolPush()
- The second Observer listened
kCFRunLoopBeforeWaiting
Event will be calledObjc_autoreleasePoolPop (), objc_autoreleasePoolPush ()
Listen to thekCFRunLoopBeforeExit
Event will be calledobjc_autoreleasePoolPop()
27. Child threads do not enable Runloop by default. Will memory leak without manual processing?
When you create a Pool in the child thread, the resulting Autorelease object will be managed by the Pool. The autoreleaseNoPage method is called if you did not create a Pool but generated an Autorelease object. In this method, you will automatically create a HotPage for you. Call Page ->add(obj) to add the object to the stack of AutoreleasePoolPage. This means no manual memory management and no memory leaks. StackOverFlow authors also say that this feature was only added to OS X 10.9+ and iOS 7+
Retain,copy,assign,weak,_Unsafe_Unretain
Strong
The: modifier refers to and holds the object, and its modifier’s reference count is incremented by one. The object will not be destroyed as long as the reference count is not zero. You can of course destroy it by forcing the variable to be nil.weak
The: modifier points to but does not hold the object, and the reference count is not incremented by one. This attribute is processed in the Runtime and can be destroyed automatically. Weak Is used to modify objects, mostly where circular references are avoided. Weak does not modify base data types.assign
: mainly used to modify basic data types, such as NSInteger and CGFloat, stored on the stack and not managed by the programmer. Assign can be used to decorate objects, but there are problems.copy
: the key words and the strong, copy more pertaining to have variable type nsstrings on immutable objects, NSArray, NSDictionary.__unsafe_unretain
Weak: Is similar to weak, but when the object is released, the pointer already stores the previous address, and the freed address becomes a zombie object. Therefore, it is unsafe to access the freed address.__autoreleasing
Assigning an object to a variable with an __autoreleasing modifier is the same as calling the object’s autorelease method when ARC is invalid.
The statement
The answer to the interview questions in this article is based on the collection of various gods, the answer is not necessarily the most comprehensive, the most appropriate, if there is a question, welcome to actively discuss.
Reference article:
www.jianshu.com/p/ca1ff3749…
Github.com/ReginaVicky…