Objective-c 类 方法声明 初始化及调用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Objective-c 类 方法声明 初始化及调用相关的知识,希望对你有一定的参考价值。
// // 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 类 方法声明 初始化及调用的主要内容,如果未能解决你的问题,请参考以下文章