——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
创建对象有两种方法,第一个是[类名 new],第二个是[[类名 alloc] init],通常的Cocoa惯例是使用第二个。
重写构造方法格式:
- (id) init
{
if(self = [super init])
{ //为子类增加属性进行初始化
}
return self;
}
1. [super init]的作用:面向对象的体现,先利用父类的init方法为子类实例的父类部分属性初始化。
2. self 为什么要赋值为[super init]:简单来说是为了防止父类的初始化方法release掉了self指向的空间 并重新alloc了一块空间(可能性很小)。这时的话,[super init]可能alloc失败,这时就不再执行if中的语句。
3. super作为消息接受者的实质:super并不是真正的指针,[super message]的实质是由self来接受父类的message。需要注意的是,[super message]中,message方法出现的self为[super message]语境中的self,即子类实例。
实例分析:
将汽车类的轮子(_lunzi)都初始化为4
Car.h声明:
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property (assign)NSString *carName;
@property int lunzi;
@end
Car.m实现:
#import "Car.h"
@implementation Car
-(id)init{
if(self = [super init]){
_lunzi = 1;
}
return self;
}
@end
main.m主函数:
#import <Foundation/Foundation.h>
#import "Car.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Car *bmw = [Car new];
NSLog(@"bmw的轮子有 %d 个",bmw.lunzi);
}
return 0;
}
运行结果:bmw的轮子有 1个
自定义构造方法
前提:
1.是对象方法,以-开头。
2.返回值类型为id或instancetype类型
3.方法名以initWith开头
4.在声明文件中声明这个方法(重写init不需要声明。)
实例分析:Car类两个属性_carName 和_lunzi初始化是赋值,Bus类继承Car,并添加了新的属性_windows,Bus类初始化时为这三个属性赋值。
Car.h声明:
<span style="font-size:24px;">#import <Foundation/Foundation.h>
@interface Car : NSObject
@property (assign)NSString *name;
@property int lunzi;
-(instancetype)initWithLunzi:(int)lunzi andName:(NSString *)name;
@end</span>
Car.m实现:
<span style="font-size:24px;">#import "Car.h"
@implementation Car
-(instancetype)initWithLunzi:(int)lunzi andName:(NSString *)name{
if (self = [super init]) {
_lunzi = lunzi;
_name = name;
}
return self;
}
@end</span>
Bus.h声明:
<span style="font-size:24px;">#import "Car.h"
@interface Bus : Car
@property int windows;
-(instancetype)initWithLunzi:(int)lunzi andName:(NSString *)name andWindows:(int)windows;
@end</span>
Bus.m实现:
<span style="font-size:24px;">#import "Bus.h"
@implementation Bus
-(instancetype)initWithLunzi:(int)lunzi andName:(NSString *)name andWindows:(int)windows{
if (self = [super initWithLunzi:lunzi andName:name]) {
_windows = windows;
}
return self;
}
@end</span>
main.m主函数:
<span style="font-size:24px;">#import <Foundation/Foundation.h>
#import "Car.h"
#import "Bus.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Car *bmw = [[Car alloc]initWithLunzi:4 andName:@"大宝马"];
NSLog(@"%@的轮子有 %d 个",bmw.name ,bmw.lunzi);
Bus *df = [[Bus alloc]initWithLunzi:16 andName:@"东方大巴士" andWindows:32];
NSLog(@"%@的轮子有 %d 个,窗户有 %d 个",df.name,df.lunzi,df.windows);
}
return 0;
}</span>
运行结果: 大宝马的轮子有 4 个
东方大巴士的轮子有 16 个,窗户有 32 个