iOS中new与alloc/init的区别

iOS之深入解析alloc、init与new的底层原理 底层探索 一、对于iOS的底层原理探索一般有三个方法实现 汇编分析 LLDB调试 源码分析 二、作为 iOS 开发者,需要关注的应该就是从应用启动到应用被 kill 掉这一整个生命周期的内容。不妨从最熟悉的 main 函数开始,一般来说,在 main.m 文件中打一个断点,左侧的调用堆栈视图应该如下图所示: 三、调用堆栈有两个注意点: 需要关闭 Xcode 左侧 Debug 区域最下面的 show only stack frames with debug symbols and between li 阅读详情

new与alloc都是初始化创建新的对象的方法,概括来说,new和alloc/init在功能上几乎是一致的,分配内存并完成初始化。差别在于,采用new的方式只能采用默认的init方法完成初始化,采用alloc的方式可以用其他定制的初始化方法。


他们两者之间到底有什么区别呢?
+ new 
{ 
id newObject = (*_alloc)((Class)self, 0); 
Class metaClass = self->isa; 
if (class_getVersion(metaClass) > 1) 
return [newObject init]; 
else 
return newObject; 
} 
 
//而 alloc/init 像这样: 
+ alloc 
{ 
return (*_zoneAlloc)((Class)self, 0, malloc_default_zone());  
} 


- init 
{ 
return self; 
} 
通过源码中我们发现,[className new]基本等同于[[className alloc] init];

区别只在于alloc分配内存的时候使用了zone.
这个zone是个什么东东呢?
它是给对象分配内存的时候,把关联的对象分配到一个相邻的内存区域内,以便于调用时消耗很少的代价,提升了程序处理速度;

为什么不推荐使用new?
不知大家发现了没有:如果使用new的话,初始化方法被固定死只能调用init。
而你想调用initXXX怎么办?没门儿!据说最初的设计是完全借鉴Smalltalk语法来的。

传说那个时候已经有allocFromZone:这个方法,
但是这个方法需要传个参数id myCompanion = [[TheClass allocFromZone:[self zone]] init];

这个方法像下面这样:
+ allocFromZone:(void *) z 
{ 
return (*_zoneAlloc)((Class)self, 0, z);  
} 
 
//后来简化为下面这个: 
+ alloc 
{ 
return (*_zoneAlloc)((Class)self, 0, malloc_default_zone());  
} 


但是,出现
个问题:这个方法只是给对象分配了内存,并没有初始化实例变量。

是不是又回到new那样的处理方式:在方法内部隐式调用init方法呢?

后来发现“显示调用总比隐式调用要好”,所以后来就把两个方法分开了。
概括来说,new和alloc/init在功能上几乎是一致的,分配内存并完成初始化。
差别在于,采用new的方式只能采用默认的init方法完成初始化,
采用alloc的方式可以用其他定制的初始化方法。


IOS 中 new 和 alloc init 的对比 主要介绍了IOS 中 new 和 alloc init 的区别的相关资料,需要的朋友可以参考下 立即下载

相关推荐

【接地系统篇】电力系统接地技术详解:从基本原理到实际应用

接地是为电流返回电源提供的一条低阻抗通道。简单来说,就是为故障电流修建一条"安全回家"的路,防止电流通过人体或其他不应带电的部件。接地系统选择原则安全性优先:TN-S系统安全性最高,适合重要场所经济性考虑:TN-C系统成本最低,适合一般工业连续性要求:IT系统供电连续性最好,适合特殊场所灵活性选择:TN-C-S系统兼顾经济与安全,应用最广。

2301_81299416的博客 2265

【iOS】alloc、init和new原理

本文浅看了OC申请内存相关方法的源码,并作一流程图总结

XY_Mckevince的博客 1054

Oracle到金仓数据库信创改造迁移实施规划方案

**性能测试和优化**:对金仓数据库的性能进行测试,根据业务负载情况进行必要的调优,确保系统能够稳定高效运行。- **数据兼容性**:评估Oracle数据库中的数据结构和金仓数据库的兼容性,明确需要重构的数据模型。- **性能测试**:通过对金仓数据库的性能测试,预估在实际业务环境下的表现,是否能达到业务需求。- **工具选择**:选择适合的迁移工具,如金仓数据库提供的迁移工具,能够提升迁移效率和准确性。- **全面迁移**:在初步迁移成功后,进行全面数据迁移,确保所有数据完整迁移到金仓数据库上。

hdrhdrjdididrr的博客 487

【IOS】关于alloc 、init和new,你真懂了吗?

关于OC的很多基础概念总是看了又看,却忘了又忘,脑海里大多只是一个笼统的概念,现在正好放假有空,腾出手来记录一下。 1.alloc和init经常放在一起写,它们分别有什么作用呢? 在初始化一个对象的时候,我们都知道要这样写 Myclass *a = [[Myclass alloc]init]; 或者也可以分开写 Myclass *a = [Myclass alloc]; a = [...

qq_36793206的博客 5638

告别安装报错!保姆级教程:用阿狸狗破戒大师V3.2.6搞定Cadence 17.4完整安装与补丁

本文提供Cadence 17.4的完整安装与破解教程,特别针对国内用户常见问题优化。从前期准备、镜像处理到阿狸狗破戒大师V3.2.6的智能破解,再到补丁管理与性能调优,详细指导每一步操作,确保一次性安装成功并提升设计效率。

weixin_30632089的博客 853

计算机考研408复试题汇总

TCP连接是全双工的,两端都可以先挥手 其中一端完成数据发送任务后,发送一个FIN包来终止,另一端针对这个FIN包回复确认包, 直到另一端也发送请求终止数据包FIN,另一端作出确认应答,并且还要发送一个ACK=1表示确认号有效,如果没有收到这个就可以进行重传.

ca1m4n的博客 1万+

new 与 alloc/init的区别

英文详解:http://macresearch.org/difference-between-alloc-init-and-new 我也是转来的:http://blog.csdn.net/ch_soft/article/details/7387731 1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init]     但是并不意味着你不会接触

abby_sheen的专栏 5803

基于Web的智能家居(源码+开题)

实践上,智能家居系统的普及和应用将极大改善人们的居住体验,提高生活质量,同时也有助于促进智能家居产业链的发展和完善,为社会经济发展注入新的活力。此外,本研究还将对基于Web的智能家居系统的用户体验进行深入研究,通过用户调研和数据分析,不断优化系统功能和界面设计,提升用户的使用体验和满意度。针对以上问题,本研究将综合运用物联网、云计算、大数据等新一代信息技术,通过系统架构设计、功能模块开发、安全性保障、用户体验优化等多个方面的研究工作,力求为基于Web的智能家居系统的研发和应用提供全面而有效的解决方案。

sryue06的博客 1908

iOS 初始化方法 alloc init 与 new 的区别

class * aclass = [[class alloc]init]; 这行代码被我们写了无数遍,同时几乎所有人都知道 class * aclass = [class new]; 的存在。 那么 [[class alloc]init]和[class new]到底有什么区别呢?该如何使用呢?照例开扒文档 https://developer.apple.com/library/mac/d

UP的博客 2098

Tesla V100 Windows 部署实战:从驱动安装到模式切换的避坑指南

本文是一份详细的Tesla V100在Windows系统下的部署实战指南。文章从硬件组装、系统选择讲起,重点阐述了驱动安装的正确方法,并深入剖析了将计算卡从TCC模式切换至WDDM模式的诱惑与潜在陷阱。最终,作者推荐保持默认TCC模式,并提供了使用nvidia-smi命令行等稳定可靠的显卡监控方案,旨在帮助用户避开常见坑点,高效利用这张专业计算卡进行AI计算等任务。

java5的博客 1743

AI硬件加速:CPU vs GPU性能对比

AI硬件加速:CPU vs GPU性能对比 关键词:人工智能、硬件加速、CPU、GPU、性能对比、硬件架构、并行计算、优化策略、项目实战 摘要: 本文将深入探讨AI

AI天才研究院 1926

ios中 new与alloc/init 的区别

在ios的开发中,对new和alloc/init的区别一直没有太多了解,在使用时也是随心情写的,今天偶然在网上看到有人介绍了,特此在这再记录一下,以便加深一下印象。前言就到这了 new是属于alloc/init的一个便利方法,在性能上alloc/init会比new创建的要强一点,为什么了?因为alloc在开辟内存时会比new多掉用一个zone,那么zone又有什么作用呢??zon

朱庆祥 1010

C#实现将DataGridView中数据导出到Excel (附完整源码)

C#实现将DataGridView中数据导出到Excel (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1596

iOS开发new与alloc/init的区别

iOS开发new与alloc/init的区别 本文是Ctril+c文章 转入地址:http://mobile.51cto.com/hot-404891.htm 1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init] 但是并不意味着你不会接触到new,在一些代码中还是会看到[className new], 还有去面试

Gamin 983

深度学习工具包 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")

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

iOS开发 new与alloc/init的区别

今天看到以前写的O-C代码,使用的n'w'w

CC的专栏 751

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

iOS new 和alloc/init 的区别

记下笔记,在开发中,创建一个对象我们有如下方式: NSObject *obj_1 = [[NSObject alloc]init]; NSObject *obj_2 = [NSObject new]; 先看看new源码: + (id)new { id newObject = (*_alloc)((Class)self, 0); Class metaClass = self->

ZXC的博客 2569

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

iOS开发之new与alloc/init的区别

1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init]。

万花筒 邪灵噶 的博客 1820

iOS中alloc/init和new的区别

1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init] 但是并不意味着你不会接触到new,在一些代码中还是会看到[className new], 还有去面试的时候,也很可能被问到这个问题。 2.那么,他们两者之间到底有什么区别呢 我们看源码: + new { id newObject = (*_alloc)((Class)self

TP465821361的博客 493

iOS new与alloc/init的区别

概括来说,new和alloc/init在功能上几乎是一致的,分配内存并完成初始化。 差别在于,采用new的方式只能采用默认的init方法完成初始化, 采用alloc的方式可以用其他定制的初始化方法。

luckxing的博客 466
上一篇: 自定义导航栏背景颜色
下一篇: KVO、KVC、NSNotificationCenter实例
番薯大佬
博客等级 码龄18年 425粉丝 867原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值