I. Custom classes for testing
@interfaceCustomedobj:nsobject+(instancetype) methodinit;@end@implementationCustomedobj+(instancetype) methodinit {customedobj*temp =[[Customedobj alloc] init]; returntemp;}- (void) Print {NSLog (@"= = = customed Object print");}- (void) dealloc {NSLog (@"object is about to be refactored");}@endSecond, the experimental conclusion2.1 Non-self-generated objects, that is, the creation method other than alloc/new/copy/mutablecopy gets the object, and assigns the value to the non-strong variable, the object will be automatically registered to the Autoreleasepool, so as not to be immediately destructor; (3.1)2.2 When assigning a value to a strong variable, the compiler does an automatic optimization for inserting objc_retainautoreleaseedreturnvalue instead of inserting retain to avoid registering to Autoreleasepool. (3.3)2.3 When accessing the weak variable, the point object is registered to Autoreleasepool. (3.3)Third, the experimental code3.1 Non-Alloc/new/copy/mutablecopy get object, automatically register to Autoreleasepool
@autoreleasepool { *weakref = [Customedobj methodinit]; object is automatically registered to Autoreleasepool and executed retaincount=1 [weakRef print]; Execute retaincount=1 } NSLog (@ " exit Autoreleasepool"); Log: = = = customed Object Print objects are about to be refactored out Autoreleasepool
3.2 Alloc/new/copy/mutablecopy Gets an object that is not automatically registered to Autoreleasepool and must be actively held to ensure that it is not refactored
@autoreleasepool { *weakref = [[Customedobj alloc] init]; compile Warning, object destructor // Print message will be sent to nil } NSLog (@ " Exit Autoreleasepool "); LOG: Object is about to be destructor exited Autoreleasepool
3.3 Weak pointer is accessed, if not registered, the system automatically registers the object to Autoreleasepool, and the reference count increases
@autoreleasepool { *strongref = [Customedobj methodinit]; the variable defaults to __strong, because compiler optimizations will not be registered to Autoreleasepool, retaincount=1 __weak customedobj *weakref = Strongref; [WeakRef print]; // calling the weak pointer registers the object with Autoreleasepool and executes the retaincount=2 } NSLog (@ " exit Autoreleasepool");
LOG: = = = customed Object Print objects are about to be refactored out Autoreleasepool
iOS memory management uses issues related to non-self-generated objects