`

new 与 alloc/init的区别

阅读更多

http://blog.csdn.net/abby_sheen/article/details/7818797

 

英文详解:http://macresearch.org/difference-between-alloc-init-and-new

我也是转来的:http://blog.csdn.net/ch_soft/article/details/7387731

1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init]
    但是并不意味着你不会接触到new,在一些代码中还是会看到[className new],
    还有去面试的时候,也很可能被问到这个问题。

2.那么,他们两者之间到底有什么区别呢,

我们看源码:

-------------------------------------------------------

+ 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是个什么东东呢?
它是给对象分配内存的时候,把关联的对象分配到一个相邻的内存区域内,以便于调用时消耗很少的代价,提升了程序处理速度;

3.而为什么不推荐使用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 的对比 1.在实际开发中很少会用到new,一般创建对象咱们看到的全是[[className alloc] init] 但是并不意味着你不会接触到new,在一些代码中还是会看到[className new], 还有去面试的时候...

    ios-iOS 未读消息角标 仿QQ拖拽 简单灵活 支持xib(源码).zip

    _badge1 = [[LFBadge alloc] init]; [_badge1 addToTabBarItem:_view1]; //BarButtonItem上加角标 _badge2 = [[LFBadge alloc] init]; [_badge2 addToBarButtonItem:self.navigationItem.rightBarButtonItem];...

    ios初级笔记

    Student *stu=[[student alloc] init]; //释放方法 [stu release] [stu setAge:20 andNo:3] NSLog(@"this age is:i% andNo:i%",[stu age],[stu no]) } return 0; } 2.点语法 以1为实例: stu.age ...

    InputPasswordLikeAlipay-源码

    添加密码输入完成代理3.new a ZSDPaymentView instance:新建一个ZSDPaymentView实例ZSDPaymentView *payment = [[ZSDPaymentView alloc]init];payment.title = @"支付密码标题";payment.goodsName = @"商品名称";...

    本地存储NSUserdefault封装(可存储各种类型)

    StudentModel *student = [[StudentModel alloc] init]; student.name = @"A"; NSArray *array = @[[InfoModel new], [InfoModel new], [InfoModel new]]; student.datas = array; [student localStoreWithKey:...

    iPhone开发、ObjectiveC_面试题目

    1、ObjC中,与alloc语义相反的方法是dealloc还是release?与retain语义相反的方法是dealloc还是release,为什么?需要与alloc配对使用的方法是dealloc还是release,为什么? 2、在一个对象的方法里面: self.name ...

    Objective C 单例模式设计源码

    第一种方式,用new方法初始化其实是第二种方式的总和,当调用new方法时,其实是先调用了alloc方法进行isa(is a pointer)操作,创建指针,指向内存中的数据结构,紧接着调用了init方法对数据进行初始化,NSObject类...

    ios开发小技巧

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; // NSString *boundary = [NSString ...

    iOS图片拉伸的方法

    UIButton *button = [[UIButton alloc] init]; // 设置尺寸 button.frame = CGRectMake(100, 200, 200, 50); // 加载图片 UIImage *image = [UIImage imageNamed:@ppm_new_shuliang.png]; // 设置背景图片 ; ...

    8192CU LINUX驱动

    #define CONFIG_NEW_SIGNAL_STAT_PROCESS //#define CONFIG_SIGNAL_DISPLAY_DBM //display RX signal with dbm #ifdef CONFIG_IOL #define CONFIG_IOL_LLT #define CONFIG_IOL_MAC #define CONFIG_IOL_BB_PHY_...

    linux内核阅读自己的笔记(用WinOrganizer工具打开)

    还没读完,作为备份。 sys_socket() --->retval = sock_create(family, type, protocol, &sock;) 1.*获取套接字的地址 ... 396 int fd = sock_alloc_fd(&newfile;); 399 int err = sock_attach_fd(sock, newfile);

    用c实现面向对象(oopc)

    t_person *const this = person.alloc(); person.init(this, name); return this; } void methodDecl_(init) char const name[] __ { this->m.name = strdup(name); } void methodDecl_(copy) t_...

    WikiApiObjectiveC:用于访问 Wikipedia API 的 Objective-C 库

    用法: 以下是您应该如何使用 WikipediaHelper 类的示例: WikipediaHelper *wikiHelper = [[WikipediaHelper alloc] init];wikiHelper.apiUrl = @"http://en.wikipedia.org";wikiHelper.delegate = self; // For ...

    虚拟网卡驱动源代码(原版)

    #include <linux/init.h> #include <linux/moduleparam.h> #include <linux/sched.h> #include <linux/kernel.h> /* printk() */ #include <linux/slab.h> /* kmalloc() */ #include <linux/errno.h> /* error ...

    Xcode-Singleton-Templates:Objective-C 的单例模板

    KO2Abc* b = [[KO2Abc alloc] init]; KO2Abc* c = [KO2Abc allocWithZone:nil]; KO2Abc* d = [KO2Abc new]; KO2Abc* e = [[KO2Abc alloc] copy]; KO2Abc* f = [[KO2Abc alloc] mutableCopy]; XCTAssertEqualObjects...

    用C编写班级成绩管理系统

    通过这次课程设计使我懂得了理论与实际相结合是很重要的,只有理论知识是远远不够的,只有把所学的理论知识与实践相结合起来,从理论中得出结论,才能真正为社会服务,从而提高自己的实际动手能力和独立思考的能力。...

    RRMessageController:RRMessageController是一个UIViewController,允许您编写带有照片作为附件的消息

    RRMessageController ...带挡块: ``Objective-C-(void)newMessage {RRSendMessageViewController * controller = [[RRSendMessageViewController alloc] init]; [controller presentController:self bl

    BasicUserNotification.m

    UILabel *label = [[UILabel alloc]init]; label.frame = CGRectMake(0, 40, 300, 200); label.numberOfLines = 0; label.textColor = [UIColor whiteColor]; label.font = [UIFont systemFontOfSize:24]; ...

    MPGNotification:MPGNotifications是一个iOS控件,可让您显示可完全自定义以满足您需要的应​​用内互动通知

    MPG通知 MPGNotifications是一个iOS控件,可让您显示...MPGNotification *notification = [[MPGNotification alloc ] init ]; MPGNotification *anotherNotification = [MPGNotification new ]; 您还可以使用以下便捷

Global site tag (gtag.js) - Google Analytics