全面解读Objective-C 中new与alloc/init的区别

摘要:

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

1.少用new多用alloc init

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

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

   来看下代码:

new 的源代码

 + 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/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的方式可以用其他定制的初始化方法。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用Objective-C纯代码实现的签到日期界面。实现的界面包括一个导航栏、一个显示当前日期的标签和一个签到按钮。 ViewController.h文件: ```objective-c #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end ``` ViewController.m文件: ```objective-c #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UILabel *dateLabel; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 设置导航栏标题 self.navigationItem.title = @"签到"; // 设置背景颜色 self.view.backgroundColor = [UIColor whiteColor]; // 创建并添加日期标签 self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)]; self.dateLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 50); self.dateLabel.textAlignment = NSTextAlignmentCenter; self.dateLabel.textColor = [UIColor blackColor]; [self.view addSubview:self.dateLabel]; // 更新日期标签的文本 [self updateDateLabel]; // 创建并添加签到按钮 UIButton *checkInButton = [UIButton buttonWithType:UIButtonTypeSystem]; checkInButton.frame = CGRectMake(0, 0, 200, 50); checkInButton.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 + 50); [checkInButton setTitle:@"签到" forState:UIControlStateNormal]; [checkInButton addTarget:self action:@selector(checkInButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:checkInButton]; } // 更新日期标签的文本 - (void)updateDateLabel { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyy年MM月dd日"; self.dateLabel.text = [formatter stringFromDate:[NSDate date]]; } // 签到按钮点击事件 - (void)checkInButtonClicked:(UIButton *)sender { // TODO: 处理签到逻辑 // 更新日期标签的文本 [self updateDateLabel]; } @end ``` 在AppDelegate.m文件,将ViewController设置为根视图控制器: ```objective-c #import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; ViewController *viewController = [[ViewController alloc] init]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; self.window.rootViewController = navigationController; [self.window makeKeyAndVisible]; return YES; } ``` 这样就完成了一个简单的签到日期界面的实现。运行程序后,可以看到一个带有日期标签和签到按钮的界面。点击签到按钮后,日期标签上的日期会更新为当前日期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值