三个文件
// Animal.h
#import <Foundation/Foundation.h>
// 视作类或接口
@interface Animal:NSObject
@property /*(readonly)*/ NSString* name;//()包裹着类型或特性
@property NSString *favFood;
@property NSString *sound;
@property float weight;
-(instancetype)/*返回本类类型*/ initWithName:(NSString*) defaultName;
-(void)getInfo;
-(float)weightInKg:(float) weightInLbs;
-(NSString*)talkToMe:(NSString*)myName;
-(int)getSum:(int)num1
nextNumber:(int)num2;//这是什么意思
@end
// Animal.m
#import "Animal.h"
// 视作实现接口的类
@implementation Animal
- (instancetype)init
{
self = [super init];
if (self) {
self.name = @"no name";
}
return self;
}
- (instancetype) initWithName:(NSString *)defaultName
{
self = [super init];
if(self){
self.name = defaultName;
}
return self;
}
-(void)getInfo{
NSLog(@"Random info");
}
-(float)weightInKg:(float)weightInLbs{
return weightInLbs * 0.4535;
}
// nextNumber 是什么
-(int)getSum:(int)num1 nextNumber:(int)num2{
return num1 + num2;
}
-(NSString*)talkToMe:(NSString *)myName{
NSString* resp = [NSString stringWithFormat:@"hello %@",myName];
return resp;
}
@end
// main.m
#import<Foundation/Foundation.h>
#import "Animal.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Animal *dog = [[Animal alloc]init];
[dog getInfo];
NSLog(@"the dog name: %@",[dog name]);
[dog setName:@"slut"];
NSLog(@"the dog name: %@",[dog name]);
Animal* cat = [[Animal alloc]initWithName:@"wet pussy"];
NSLog(@"the cat name: %@",[cat name]);// 调用方法或属性都是[]
}
return 0;
}