码迷,mamicode.com
首页 > 其他好文 > 详细

Objective-C - 自定义构造方法

时间:2015-04-19 10:15:06      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:objective   自定义构造方法   

自定义构造方法

@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;
}

Objective-C - 自定义构造方法

标签:objective   自定义构造方法   

原文地址:http://blog.csdn.net/wangzi11322/article/details/45126311

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!