【转】iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的autorelease pool

Colmap参数调优实战:如何通过5个关键设置提升3D重建精度 本文深入探讨Colmap参数调优实战,通过5个关键设置显著提升3D重建精度。重点解析特征匹配参数、BA优化配置、初始化策略、资源分配及动态调整方法,结合量化数据和实际案例,帮助开发者精准优化重建流程,适用于古建筑扫描、无人机航拍等多种场景。 阅读详情

版权声明

此文版权归作者Vince Yuan (vince.yuan#gmail.com)所有。欢迎非营利性转载,转载时必须包含原始链接http://vinceyuan.cnblogs.com/,且必须包含此版权声明的完整内容。

版本 1.1 发表于2010-03-08

 

四 系统自动创建新的autorelease pool

在生成新的Run Loop的时候,系统会自动创建新的autorelease pool(非常感谢网友hhyytt和neogui的提醒)。注意,此处不同于xcode在新建项目时自动生成的代码中加入的autorelease pool,xcode生成的代码可以被删除,但系统自动创建的新的autorelease pool是无法删除的(对于无Garbage Collection的环境来说)。Objective-C没有给出实现代码,官方文档也没有说明,但我们可以通过小程序来证明。

在这个小程序中,我们先生成了一个autorelease pool,然后生成一个autorelease的ClassA的实例,再在一个新的run loop中生成一个autorelease的ClassB的对象(注意,我们并没有手动在新run loop中生成autorelease pool)。精简的示例代码如下,详细代码请见附件中的memman-run-loop-with-pool.m。

int main(int argc, char**argv) 

{

         NSLog(@"create an autorelasePool\n");

         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];   

 

         NSLog(@"create an instance of ClassA and autorelease\n");

         ClassA *obj1 = [[[ClassA alloc] init] autorelease];

         NSDate *now = [[NSDate alloc] init];

         NSTimer *timer = [[NSTimer alloc] initWithFireDate:now

                   interval:0.0

                   target:obj1

                   selector:@selector(createClassB)

                   userInfo:nil

                   repeats:NO];

         NSRunLoop *runLoop = [NSRunLoop currentRunLoop];

         [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

         [timer release];

         [now release];

         [runLoop run]; //在新loop中调用一函数,生成ClassB的autorelease实例

 

         NSLog(@"releasing autorelasePool\n");

         [pool release];

         NSLog(@"autorelasePool is released\n");

         return 0;

} 

输出如下:

create an autorelasePool

create an instance of ClassA and autorelease

create an instance of ClassB and autorelease

ClassB destroyed

releasing autorelasePool

ClassA destroyed

autorelasePool is released

注意在我们销毁autorelease pool之前,ClassB的autorelease实例就已经被销毁了。

有人可能会说,这并不能说明新的run loop自动生成了一个新的autorelease pool,说不定还只是用了老的autorelease pool,只不过后来drain了一次而已。我们可以在main函数中不生成autorelease pool。精简的示例代码如下,详细代码请见附件中的memman-run-loop-without-pool.m。

int main(int argc, char**argv) 

{

         NSLog(@"No autorelasePool created\n");

 

         NSLog(@"create an instance of ClassA\n");

         ClassA *obj1 = [[ClassA alloc] init];

         NSDate *now = [[NSDate alloc] init];

         NSTimer *timer = [[NSTimer alloc] initWithFireDate:now

                   interval:0.0

                   target:obj1

                   selector:@selector(createClassB)

                   userInfo:nil

                   repeats:NO];

         NSRunLoop *runLoop = [NSRunLoop currentRunLoop];

         [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

         [timer release];

         [now release];

         [runLoop run]; //在新loop中调用一函数,生成ClassB的autorelease实例

         NSLog(@"Manually release the instance of ClassA\n");

         [obj1 release];

 

         return 0;

} 

输出如下:

No autorelasePool created

create an instance of ClassA

create an instance of ClassB and autorelease

ClassB destroyed

Manually release the instance of ClassA

ClassA destroyed

我们可以看出来,我们并没有创建任何autorelease pool,可是ClassB的实例依然被自动销毁了,这说明新的run loop自动创建了一个autorelease pool,这个pool在新的run loop结束的时候会销毁自己(并自动release所包含的对象)。

 

补充说明

在研究retain count的时候,我不建议用NSString。因为在下面的语句中,

NSString *str1 = @”constant string”;

str1的retain count是个很大的数字。Objective-C对常量字符串做了特殊处理。

当然,如果你这样创建NSString,得到的retain count依然为1

NSString *str2 = [NSString stringWithFormat:@”123”];

利用DRONEKIT-SITL + MAVPROXY + QGroundControl模拟飞行 dronekit: 一种用于无人机控制的python库。 dronekit-sitl:一种本地仿真工具,相当于本地虚拟化了一个无人机。 mavproxy:数据转发软件(类似于插线板的感觉,一个输入,多个相同的输出)。打开一个Anaconda prompt 首先激活相应的环境 然后运行如下命令: 保持2中的Anaconda prompt处于运行状态,另打开一个Anaconda prompt窗口,运行如下命令: tcp:127.0.0.1:5760: SITL默认端口,作为mavproxy的输入,把输入数据转发 阅读详情

相关推荐

STM32 ADC+DMA实战:手把手教你驱动XGZP6847A压力传感器(附完整代码)

本文详细介绍了如何使用STM32的ADC和DMA外设驱动XGZP6847A压力传感器,包括硬件连接、ADC配置、DMA高效传输实现以及数据处理与校准方法。通过实战案例和完整代码,帮助开发者快速掌握高精度压力数据采集技术,适用于工业控制和医疗设备等领域。

weixin_42570484的博客 406

iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的aut...

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33701251的博客 147

手把手教学,Python 游戏编程之实现飞机大战(含源代码)

我想大家都是有玩过类似飞机大战的射击类游戏,也享受目标被消除通过后带来的愉悦感。那么如果用Python来实现飞机大战游戏?下面就跟大家一起用Python来做一个小游戏,不仅可以从中感受到乐趣,还可以提升自己的能力。

veratata的博客 1万+

autorelease pool 原理剖析

autorelease pool 原理剖析 (其实很简单的,一定要坚持看下去,否则 还是不能理解 Objective-C 的内存管理机制。) 6.1 autorelease pool 不是天生的,需要手动创立。只不过在新建一个 ip hone 项目时,xcode 会自动帮你写好。autorelease pool 的真名是 NSAutorele asePool。 NSAutorelease

u010912122的专栏 663

Photoscan+Smart3D+CC组合建模实战:如何用三款工具打造高精度实景模型

本文详细介绍了如何整合Photoscan、Smart3D和ContextCapture三款软件,构建高效高精度的实景三维建模工作流。通过利用Photoscan稳健的空三解算、Smart3D精准的刺点优化,以及ContextCapture强大的最终建模能力,该方案能有效应对复杂地形与海量数据,显著提升模型质量与生产效率,适用于测绘、文化遗产数字化等专业领域。

weixin_29230649的博客 104

comsol 多物理场仿真流程-以开关柜为例

1、主要方法 在SolidWorks中对于开关柜的内部与外部结构进行建模,生成能够导入软件计算的3D模型。将SolidWorks中的模型导入comsol软件中,设置参数进行多物理场耦合仿真。 1、具体步骤 删除高压开关柜中对其内部电磁环境无较大影响的结构,如低压测量柜、断路器内部结构等。 导入模型:将厂家提供的3D模型转化为solidworks结构模型。 修复模型:修复已转化模型中转化错误的部分、修复已转化模型中非实体部分、修复已转化模型中重叠实体部分 化简模型:去除过于...

健忘16的博客 7020

为什么要手动创建autoreleasepool

autorelase的本质就是延迟调用release方法 NSThread和NSOperationQueue开辟子线程需要手动创建autoreleasepool,GCD开辟子线程不需要手动创建autoreleasepool,因为GCD的每个队列都会自行创建autoreleasepool 用@autoreleasepool是有用的。 正常情况下,你创建的变量会在超出其作用域的时候被释放掉。 而如果你的函数写的很长,在你函数运行过程中出现很多中间变量,占据了大量的内存,怎么办? 用@autoreleasepoo

More reading and learning to become excellent 639

matlab中高频变压器怎么找,干货|手把手教你绕制高频变压器

原标题:干货|手把手教你绕制高频变压器绕制一个变压器所需材料:磁芯、骨架、各种铜线、麦拉胶带。变压器参数:磁芯:EE22原边:134T(1-3脚),辅助:32T(5-4脚),输出:15T(10-9脚)原边电感:1380±10%uH漏感:≤44uH引脚分布图: 特别注意:绕制方法为网上下载,其中变压器绕制方法是对的,但其中存在着很多问题(比如,正规变压器的绕组的头和尾是要添加铁氟龙套管的,每一层之间...

weixin_30895121的博客 2127

iPhone/Mac Objective-C内存管理教程和原理剖析

版权声明 此文版权归作者Vince Yuan (vince.yuan#gmail.com)所有。欢迎非营利性转载,转载时必须包含原始链接http://vinceyuan.cnblogs.com/,且必须包含此版权声明的完整内容。 版本1.1发表于2010-03-08 前言 初学objectice-C的朋友都有一个困惑,总觉得对objective-C的内存管理机制琢磨不...

168

通过WorkVisual连接KUKA机器人的具体方法

通过WorkVisual连接KUKA机器人的具体方法

Robot_PLC_HMI_Automation 6850

FLACS-CFD 气云爆炸模拟全流程工况构建指南:从泄漏到爆炸

摘要: 本文详细介绍了使用FLACS-CFD模拟气云爆炸的全流程构建方法,重点解决泄漏模拟到爆炸模拟的气云文件传递问题。核心步骤包括: 项目规划:明确泄漏源(甲烷管道腐蚀泄漏)和爆炸场景,建立标准目录结构; 网格设计:泄漏与爆炸模拟需采用兼容的网格,爆炸域应为泄漏域的子区域且网格划分一致; 泄漏模拟配置:通过.inp文件定义几何、网格、风场、燃料及泄漏源参数,确保输出爆炸所需的气云文件(*.uni/*.fla); 关键设置:统一燃料名称、时间点匹配、路径正确性,避免版本兼容性问题。

huanghm88的专栏 767

【转】iPhone/Mac Objective-C内存管理教程和原理剖析

版权声明 此文版权归作者Vince Yuan (vince.yuan#gmail.com)所有。欢迎非营利性转载,转载时必须包含原始链接http://vinceyuan.cnblogs.com/,且必须包含此版权声明的完整内容。 版本 1.1 发表于2010-03-08 前言 初学objectice-C的朋友都有一个困惑,总觉得对objective-C的内存管理机制琢...

北极 124

YOLOv8自定义训练:车牌识别全流程(从标注到推理,附可视化代码)

车牌检测全流程实践指南 摘要:本文详细介绍了基于YOLOv8的车牌检测完整实现方案。针对车牌检测中的三大难点(小目标、多角度、光照变化),提供了从数据准备到模型部署的全流程解决方案。重点包括:1)数据采集与标注规范;2)针对小目标的YOLOv8模型优化配置;3)K-means锚框聚类方法;4)训练参数调优策略。通过实际验证,该方法可获得95%以上的检测准确率,并附有完整的代码实现和可视化工具,便于开发者快速复现应用。 (字数:149字)

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 851

iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的autorelease pool

<br />iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的autorelease pool Posted on 2010-03-08 21:14 Vince Yuan 阅读(1601) 评论(2) 编辑 收藏 <br />版权声明<br />此文版权归作者Vince Yuan (vince.yuan#gmail.com)所有。欢迎非营利性转载,转载时必须包含原始链接http://vinceyuan.cnblogs.com/,且必须包含此版权声明的完整内容。<br

安迪·潘 的专栏 774

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

iPhone/Mac Objective-C内存管理教程和原理剖析 【四、系统自动创建新的autorelease pool】

四 系统自动创建新的autorelease pool 在生成新的Run Loop的时候,系统会自动创建新的autorelease pool(非常感谢网友hhyytt和neogui的提醒)。注意,此处不同于xcode在新建项目时自动生成的代码中加入的autorelease pool,xcode生成的代码可以被删除,但系统自动创建的新的autorelease pool是无法删除的(对于无Garb

947

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

上一篇: 【转】iPhone/Mac Objective-C内存管理教程和原理剖析(三)@property (retain)和@synthesize的默认实现
下一篇: XCode的一些调试技巧
view1221
博客等级 码龄19年 4粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值