因为一些不恰当的因素,所有自动生成的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; 
 
 
} 
 
 
 |   
        
 
    
    
    
     
 
 |