自定义构造方法的规范:1、一定是对象方法,一定以 - 开头
2、返回值一般是id类型
3、方法名一般以initWith开头
Person类的声明中:
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- @property NSString *name;
- @property int age;
- - (id)initWithName:(NSString *)name;
- - (id)initWithAge:(int)age;
- // initWithName:andAge:
- - (id)initWithName:(NSString *)name andAge:(int)age;
- @end
复制代码 Person类的实现中:
- #import "Person.h"
- @implementation Person
- - (id)init
- {
- if ( self = [super init] )
- {
- _name = @"Jack";
- }
- return self;
- }
- - (id)initWithName:(NSString *)name
- {
- if ( self = [super init] )
- {
- _name = name;
- }
-
- return self;
- }
- - (id)initWithAge:(int)age
- {
- if ( self = [super init] )
- {
- _age = age;
- }
- return self;
- }
- - (id)initWithName:(NSString *)name andAge:(int)age
- {
- if ( self = [super init] )
- {
- _name = name;
- _age = age;
- }
- return self;
- }
- @end
复制代码
|
|