自定义构造方法
@interface Person : NSObject
@property NSString *name;
@property int age;
/*
自定义构造方法的规范
1.一定是对象方法,一定以 - 开头
2.返回值一般是id类型
3.方法名一般以initWith开头
*/
- (id)initWithName:(NSString *)name;
- (id)initWithAge:(int)age;
// initWithName:andAge:
- (id)initWithName:(NSString *)name andAge:(int)age;
@end
#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
#import "Person.h"
@interface Student : Person
@property int no;
- (id)initWithNo:(int)no;
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no;
@end
#import "Student.h"
@implementation Student
- (id)initWithNo:(int)no
{
if ( self = [super init] )
{
_no = no;
}
return self;
}
// 父类的属性交给父类方法去处理,子类方法处理子类自己的属性
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
// 将name、age传递到父类方法中进行初始化
if ( self = [super initWithName:name andAge:age])
{
_no = no;
}
return self;
}
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
if ( self = [super init] )
{
_no = no;
//_name = name;
self.name = name;
self.age = age;
//[self setName:name];
//[self setAge:age];
}
return self;
}
@end
#import "Person.h"
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *p = [[Student alloc] initWithName:@"Jim" andAge:29 andNo:10];
NSLog(@"00000");
}
return 0;
}
时间: 2024-11-05 12:30:51