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

Objective-c 类 方法声明 初始化及调用

时间:2016-05-16 21:25:17      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:

//
//  Student.h
//  OOP
//
//  Created by acgity on 16/5/16.
//  Copyright © 2016年 acgity. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef enum {
    male,female
} SEX;

@interface Student : NSObject
{
    @public
    NSString *_name;
    int _age;
    SEX _sex;
}

+(void)walk;
-(void)talk;
-(instancetype)init;
-(instancetype)initWithName:(NSString *)name withAge:(int)age withSex:(SEX)sex;

@end

//
//  Student.m
//  OOP
//
//  Created by acgity on 16/5/16.
//  Copyright © 2016年 acgity. All rights reserved.
//

#import "Student.h"

@implementation Student

-(instancetype)init{
    self = [super init];
    if(self != nil){
        self -> _name = @"acgity";
        self -> _age = 23;
        self -> _sex = female;
    }
    return self;
}

-(instancetype)initWithName:(NSString *)name withAge:(int)age withSex:(SEX)sex{
    self = [super init];
    if(self != nil){
        self->_name = name;
        self->_age = age;
        self->_sex = sex;
    }
    return self;
}

-(void)talk {
    NSString *flag = self->_sex == male ? @"girl" : @"boy";
    NSLog(@"Hi,I‘m a %@ named %@ %d years old...",flag,_name,_age);
}

+(void)walk {
    NSLog(@"I‘m walking now...");
}
@end

//
//  main.m
//  OOP
//
//  Created by acgity on 16/5/16.
//  Copyright © 2016年 acgity. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]) {
    
    Student *df = [[Student alloc] init];
    [df talk];
    [Student walk];
    
    Student *ini = [[Student alloc] initWithName:@"tony" withAge:32 withSex:male];
    [ini talk];
    [Student walk];
    
    return 0;
}

2016-05-16 18:46:34.287 OOP[3140:120047] Hi,I‘m a boy named acgity 23 years old...

2016-05-16 18:46:34.288 OOP[3140:120047] I‘m walking now...

2016-05-16 18:46:34.288 OOP[3140:120047] Hi,I‘m a girl named tony 32 years old...

2016-05-16 18:46:34.288 OOP[3140:120047] I‘m walking now...

Program ended with exit code: 0

Objective-c 类 方法声明 初始化及调用

标签:

原文地址:http://www.cnblogs.com/acpit/p/5499149.html

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