您的位置:首页 > 移动开发 > Objective-C

Object-C 便利构造器

2015-07-27 13:18 459 查看

Object-C 便利构造器

对类来说

1.初始化方法 系统的

2.自定义初始化方法

-(id)initWithWithName:(NSSTRING *)name ;


3.便利构造器(初始化方法)

作用:在外界构造类的对象时,开发者 不需要关心其生命周期

4.OC中方法

静态方法 (类方法) 标识: +

实例方法 标识: -

5.在类的外边调用

对于 类方法 来说,它调用方式是用 来调用

对于 实例方法 来说,它调用方式是用 对象 调用

新建 Student.h 与 Student.m文件

Student.h文件

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
NSString *_sID ;
}

@property (nonatomic,strong)NSString *name ;

@property (nonatomic,assign)NSInteger age ;

-(id)initWithName:(NSString *)name Age:(NSInteger)age;

-(void)sayHello ;

//便利构造器
+(Student *)studentWithName:(NSString *)name Age:(NSInteger)age;


1.根据需要创建便利构造器

2.根据需要来创建便利构造器相对应的方法

Student.m文件:

#import "Student.h"

@implementation Student

-(id)init
{
if (self = [super init]) {

}
return self;
}

-(id)initWithName:(NSString *)name Age:(NSInteger)age
{
if (self = [super init])
{
self.name = name;
self.age = age ;
[self sayHello];
}
return self;
}

//便利构造器
//相当于在类的里面再写一个跟类无关的方法
+(Student *)studentWithName:(NSString *)name Age:(NSInteger)age
{
//在类中用类本身自带的初始化方法来构造对象,然后将对象当做返回值抛出
Student *st = [[Student alloc]initWithName:name Age:age];
return st;

/*
在类的内部,对于静态来讲:
1.它不能访问类的实例变量及属性
2.不能用self调用类自带方法和属性
*/
}

-(void)sayHello
{
NSLog(@"hello");
}

@end


main.m文件

#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {

//利用便利构造器生成st对象
Student *st = [Student studentWithName:@"jack" Age:25];

//利用便利初始化方法生成st1对象
Student *st1 = [[Student alloc]nitWithName:@"jack" Age:25];
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  OC-便利构造器