@fiy-fish
2015-07-14T12:50:07.000000Z
字数 926
阅读 1296
Objective-c
// main.m
// day01-04-setter和getter方法
//
// Created by Aaron on 15/7/1.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Cat.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Cat *cat = [Cat alloc];
[cat setCatAge:100];
NSLog(@"猫的年龄:%ld",[cat catAge]);
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Cat : NSObject
{
NSInteger _catAge;
}
//定义带参的方法
//-(返回值)方法名:(参数类型)参数名;
//test1 是方法名
-(void)test1;
//writeAge: 是方法名
-(void)writeAge:(NSInteger)age;
//andWeight 叫做标签,用作参数说明
//writeAge: andWeight: 方法名(方法签名)
-(void)writeAge:(NSInteger)age andWeight:(NSInteger)weight;
//设值方法 setter
//专门用来给实例变量赋值
//set+实例变量的名字
-(void)setCatAge:(NSInteger)newAge;
//取值方法 getter
//专门用来获取实例变量的值
//getter 方法的标准写法就是 -(数据类型)实例变量名;
-(NSInteger)catAge;
@end
#import "Cat.h"
@implementation Cat
-(void)setCatAge:(NSInteger)newAge
{
if(newAge>4)
{
_catAge = 4;
}
else
{
_catAge = newAge;
}
NSLog(@"%ld",_catAge);
}
-(NSInteger)catAge
{
return _catAge;
}
@end