-----------android培训、java培训、iOS培训、.Net培训、期待与您交流!------------
上一篇介绍OC的self对象时,使用了如下代码
Person *p = [[Person alloc] init];
[p setAge:23];
NSLog(@"%@",p);
Person是一个OC对象,alloc是为该对象分配内存的方法,而init就是对象的构造方法。构造方法就是用来完成 对象的初始化操作,Person类中并没有init方法,但是因为Person类是继承自NSObject类的,在NSObject类中声明了init方法
init方法是一个对象方法,且返回类型是id,id是万能指针,能指向\操作任何OC对象,id的声明如下
可以看出id是已经是一个指向objc_object的指针对象,objc_object结构体顾名思义就是指OC对象,而且因为是指针,所以id也不需要加*。
有时候只使用NSObject类的默认init有时候是不够的,比如
//
// Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
int _no; // 学号
int _age; // 年龄
}
// 成员变量的getter && setter方法
- (int)no;
- (void)setNo:(int)no;
- (int)age;
- (void)setAge:(int)age;
@end
//
// Student.m
#import "Student.h"
@implementation Student
// 成员变量的getter && setter 方法
- (int)age
{
return _age;
}
- (void)setAge:(int)age
{
self->_age = age;
}
- (int)no
{
return _no;
}
- (void)setNo:(int)no
{
self->_no = no;
}
@end
现在一个班级50有个人,学号为1-50,如果只用默认的构造方法,可以这么写
//
// main.m
#import <Foundation/Foundation.h>
#import "Student.h"
#define CLASS_NUM 50 // 班级人数
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for (int i = 0; i < CLASS_NUM ; i++)
{
Student *s = [[Student alloc] init]; // 声明一个Student对象的局部变量
s.no = i + 1; // 为Student对象的no赋值 < 1 >
[mutableArray insertObject:s atIndex:i]; // Student对象加入数组
}
// 打印 mutableArray数组元素的no成员变量
for (int i = 0; i < CLASS_NUM; i++) {
NSLog(@"%d",[mutableArray[i] no]);
}
}
return 0;
}
但是如果在Student中添加一个以学号为形参的自定义构造方法initWithNo,则< 1 >处的两句话可以合并成
Student *s = [[Student alloc] initWithNo:(i + 1)];
Student.h添加
// 自定义init方法
- (id)initWithNo:(int)no;
Student.m添加
// 自定义init方法
- (id)initWithNo:(int)no
{
if (self = [super init]) {
self.no = no;
}
return self;
}
在入学blog02中的Graphic类的自定义构造方法是
- (Graphic *) initWithGname:(NSString *)gname andCategory:(WCategory)category;
返回值使用了 Graphic * 类型,应该使用id
构造方法也可以被重写,比如一个班的同学年龄大部分是相同的
Student.h
// 重写init方法
- (id) init;
Student.m
// 重写init方法
- (id) init
{
if (self = [super init]) {
self.age = 23;
}
return self;
}