课程来自慕课网Visitor.zc老师
面向对象与函数
- main.m
#import <Foundation/Foundation.h>
#import "People.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 调用方法使用 []
People *p1 = [[People alloc] init];
[p1 report]; // name:visitor age:18
int res1 = [p1 showWithA:10];
NSLog(@"res1=%d",res1); // res1=10
int res2 = [p1 showWithA:10 andB:20];
NSLog(@"res2=%d",res2); // res2=30
People *p2 = [[People alloc] initWithName:@"Admin" andAge:30];
[p2 report]; // name:Admin age:30
return 0;
}
}
- People.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface People : NSObject
/*
-: 对象方法 使用对象名调用
+: 类方法 使用类名调用
(void) report - void: 函数返回值类型
(int)a - (int): 参数类型 a: 参数名
函数名 - 1.report: 2.say: 3.showWithA 4.showWithA: andB:
*/
- (void) report;
+ (void) say;
- (int) showWithA:(int)a;
- (int) showWithA:(int)a andB:(int)b;
// 初始化方法
- (instancetype) init;
// 自定义初始化方法
- (instancetype) initWithName:(NSString *)name andAge:(int)age;
@end
NS_ASSUME_NONNULL_END
- People.m
#import "People.h"
@implementation People
{
NSString *_name;
int _age;
}
- (void) report
{
//NSLog(@"report");
//_name = @"reporter";
NSLog(@"name:%@ age:%d",_name,_age);
// 对象方法中调用类方法
//[People say];
}
+ (void) say
{
// 加号方法(类方法)无法调用成员变量
NSLog(@"say something");
// 类方法中调用对象方法,需要实例化
//[[People alloc] report];
}
- (int) showWithA:(int)a
{
return a;
}
- (int) showWithA:(int)a andB:(int)b
{
return a + b;
}
- (instancetype)init
{
self = [super init];
if (self) {
_name = @"visitor";
_age = 18;
}
return self;
}
- (instancetype) initWithName:(NSString *)name andAge:(int)age
{
self = [super init];
if (self) {
_name = name;
_age = age;
}
return self;
}
@end