A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 维维轩 中级黑马   /  2015-10-28 09:45  /  983 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

因为一些不恰当的因素,所有自动生成的set,get方法已经不能满足要求,所以就要重写set或get方法,来达到我们的要求
举例说明问题
//Gun.h文件中
#import <Foundation/Foundation.h>


@interface Gun : NSObject



@property int bulletCount;//子弹数量(加强版)



@end



Gun.m文件中


#import "Gun.h"



@implementation Gun



//重写set方法,记住不要随便重写系统的方法





//当set,get方法都重写了之后,属性值也不会再自动生成,要想使用属性值,必须手动生成


-(void)setBulletCount:(int)bulletCount{


    //过滤



    if (bulletCount >0) {


        _bulletCount = bulletCount;


    }else{


        _bulletCount = 0;


    }


}






//-(int)bulletCount{


//    return _bulletCount;


//}


@end



main.m文件中


#import <Foundation/Foundation.h>


#import "Gun.h"



int main(int argc, const char * argv[])


{




    Gun *gun1 = [Gun new];


   


    gun1.bulletCount = -4;


   


    NSLog(@"子弹个数%i",gun1.bulletCount);


    return 0;


}

6 个回复

倒序浏览
----------------------------------------好
回复 使用道具 举报
--------------------------------------好
回复 使用道具 举报
代码行距好大。。。
回复 使用道具 举报
代码写的不怎么好看
回复 使用道具 举报
代码写的很强大。。。
回复 使用道具 举报
恩,看得有点费劲,这样写代码在公司会被骂的。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马