oc set/get方法

新建一个“Cocoa Touch Class”文件,命名为People

People.h 写入

@interface People : NSObject
@property   int age;
@end

People.m写入(其实是自动产生的)

@implementation People

@end

使用场合:

int main(int argc, char * argv[]) {
    People *p=[[People alloc]init];
    p.age=10;//直接使用set方法
    NSLog(@"age %d\n",p.age);//直接使用get方法
    [p setAge:20];//调用set方法
    NSLog(@"age %d\n",[p age]);//调用get方法
    int test;
    test=1;
    
    NSLog(@"age %d\n",test);

    
}

 

手动写入set/get方法

上例中可以通过@property方式自动会产生set/get方法,我们也可以通过手动写入set/get方法。

修改People.h

@interface People : NSObject{
    int _age;
}
@property   int age;
@end

修改People.m

@implementation People
-(void)setAge:(int)age{
    NSLog(@"set age");
    _age=age;
}
-(int)age{
    NSLog(@"get age");
    return _age;
}
@end

通过个性,再执行程序,发现我们手动写的set/get方法的输出了日志。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值