为什么内存没有增加?物理分配内存了吗?
Why memory is not increasing?Has memory allocated physically?
我已经测试了 Xcode 10.3
中的代码
- (void)loopObjectMalloc {
while (1) {
NSObject *obj = [[NSObject alloc] init];
}
}
我预计发生了OOM,但内存没有增加。 alloc函数不是memset到物理内存吗?
默认情况下,自动引用计数 (ARC) 处于启用状态。所以obj
会在每次循环结束时释放内存,使内存不增加。
obj
不需要等待每个循环完成。
- (void)loopObjectMalloc {
while (1) {
// At the beginning of each loop, `obj` is created.
NSObject *obj = [[NSObject alloc] init];
// End of the loop, obj is released due to out of scope.
}
// End of function.
}
不需要自动释放池来释放你的对象。 release
将在编译时自动插入到您的代码中。
retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including [super dealloc] when dealloc is overridden.
https://en.wikipedia.org/wiki/Automatic_Reference_Counting#Objective-C
注意:如果你想看到OOM,请关闭ARC。
您可以使用桥接函数从 ARC 获取所有权:
- (void)loopObjectMalloc {
while (1) {
CFTypeRef obj = CFBridgingRetain([[NSObject alloc] init]);
}
}
我已经测试了 Xcode 10.3
中的代码- (void)loopObjectMalloc {
while (1) {
NSObject *obj = [[NSObject alloc] init];
}
}
我预计发生了OOM,但内存没有增加。 alloc函数不是memset到物理内存吗?
默认情况下,自动引用计数 (ARC) 处于启用状态。所以obj
会在每次循环结束时释放内存,使内存不增加。
obj
不需要等待每个循环完成。
- (void)loopObjectMalloc {
while (1) {
// At the beginning of each loop, `obj` is created.
NSObject *obj = [[NSObject alloc] init];
// End of the loop, obj is released due to out of scope.
}
// End of function.
}
不需要自动释放池来释放你的对象。 release
将在编译时自动插入到您的代码中。
retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including [super dealloc] when dealloc is overridden.
https://en.wikipedia.org/wiki/Automatic_Reference_Counting#Objective-C
注意:如果你想看到OOM,请关闭ARC。
您可以使用桥接函数从 ARC 获取所有权:
- (void)loopObjectMalloc {
while (1) {
CFTypeRef obj = CFBridgingRetain([[NSObject alloc] init]);
}
}