1.类数据受保护的情况
#import<Foundation/Foundation.h>
@interface FZFStudent : NSObject
{
NSString *_name;
NSInteger _age;
}
-(void)say;
@end
#import"FZFStudent.h"
@implementation FZFStudent
-(void)say
{
NSLong(@"name=%@,age=%d",_name,_age)
}
@end
#import<Foundation/Foudation.h>
#import"FZFStudent.h"
int main(int argc, const char * argv[]){
autoreleasepool{
FZFStudent *zs=[[FZFStudent alloc]init];
[zs say];
}
return 0;
}
运行结果:
name=(null),age=0
//这种情况下类的数据受保护,显示结果都为空的.
2.将数据公开@public
#import<Foundation/Foundation.h>
@interface FZFStudent : NSObject
{
@public
NSString *_name;
NSInteger _age;
}
-(void)say;
@end
#import"FZFStudent.h"
@implementation FZFStudent
-(void)say
{
NSLong(@"name=%@,age=%d",_name,_age)
}
@end
#import<Foundation/Foudation.h>
#import"FZFStudent.h"
int main(int argc, const char * argv[]){
autoreleasepool{
FZFStudent *zs=[[FZFStudent alloc]init];
zs->_name=@"张三";
zs->_age=22;
[zs say];
}
return 0;
}
运行结果:
name=张三,age=22
//这种情况下是将类中的数据公开@public
3.运用setter 和 getter
类中的数据赋值
类中的数据是保护起来的,需提供行为进行赋值
setter和getter函数
#import<Foundation/Foundation.h>
@interface FZFStudent : NSObject
{
NSString *_name;
NSInteger _age;
}
-(void)say;
-(void)setName:(NSString *)name;//设置器
-(NSString *)name;//访问器
-(void)setAge:(NSInteger)age;//访问器
//-(void)setName:(NSString *)name andAge:(NSInteger)age;
@end
#import"FZFStudent.h"
@implementation FZFStudent
-(void)say
{
NSLog(@"name=%@,age=%d",_name,_age);
}
-(void)setName:(NSString *)name
{
_name = name;
}
-(NSString *)name
{
return _name;
}
-(void)setAge:(NSInteger)age
{
_age = age;
}
-(void)age
{
return _age;
}
/*-(void)setName:(NSString *)name andAge:(NSInteger)age
{
_name=name;
_age=age;
}
*/
@end
#import<Foundation/Foudation.h>
#import"FZFStudent.h"
int main(int argc, const char * argv[]){
autoreleasepool{
FZFStudent *lisi=[[FZFStudent alloc]init];
[lisi setName:@"李四"];
[lisi setAge:18];
//[lisi setName:@"李四" andAge:18];
[lisi name];//访问了-(NSString *)name这个行为
[lisi age];//访问了-(void)age这个行为
NSLog(@"name=%@,age=%d",[lisi name],[lisi age]);
[lisi say];
}
return 0;
}
运行结果:
name=李四,age=18
name=李四,age=18
//运用set的函数提供行为进行赋值
4.运用点操作符(.)
类的赋值(点操作符,其实是setter和getter的糖果)
#import<Foundation/Foundation.h>
@interface FZFRectangle : NSObject
{
NSInteger _width;
NSInteger _height;
}
-(void)setWidth:(NSInteger)w;
-(void)setHeight:(NSInteger)h;
-(NSInteger)w;
-(NSInteger)h;
-(NSInteger)area;
@end
#import"FZFRectangle.h"
@implementation FZFRectangle
-(void)setWidth:(NSInteger)w
{
_width=w;
}
-(void)setHeight:(NSInteger)h
{
_height=h;
}
-(NSInteger)w
{
return _width;
}
-(NSInteger)h
{
return _height;
}
-(NSInteger)rectangle
{
return _width*_height;
}
@end
#import<Foundation/Foundation.h>
#import"FZFRectangle.h"
int main(int argc, const char * argv[]){
autoreleasepool{
/*FZFRectangle *rect=[[FZFRectangle alloc]init];
[rect setWidth:200];
[rec setHeight:100];
*/
rect._width=200;
/*.点操作符其实是一个行为的调用
NSInteger w = rect.width
*/
rect._height=100;
NSLog(@"这个长方形的面积是:%d",[rect area]);
}
return 0;
}
运行的结果:
这个长方形的面积是:20000