@property与@synthesize
@interface Person : NSObject
{
int _age;
// int age;
int _height;
double _weight;
NSString *_name;
}
// @property:可以自动生成某个成员变量的setter和getter声明
@property int age;
//- (void)setAge:(int)age;
//- (int)age;
@property int height;
//- (void)setHeight:(int)height;
//- (int)height;
- (void)test;
@property double weight;
@property NSString *name;
@end
#import "Person.h"
@implementation Person
// @synthesize自动生成age的setter和getter实现,并且会访问_age这个成员变量
@synthesize age = _age;
@synthesize height = _height;
@synthesize weight = _weight, name = _name;
@end
车类
#import <Foundation/Foundation.h>
@interface Car : NSObject
{
//int _speed;
//int _wheels;
}
@property int speed;
@property int wheels;
//@property int speed, wheels;
- (void)test;
@end
#import "Car.h"
@implementation Car
//@synthesize speed = _speed, wheels = _wheels;
// 会访问_speed这个成员变量,如果不存在,就会自动生成@private类型的_speed变量
@synthesize speed = _speed;
@synthesize wheels = _wheels;
- (void)test
{
NSLog(@"速度=%d", _speed);
}
@end
狗类
@interface Dog : NSObject
@property int age;
@end
#import "Dog.h"
@implementation Dog
- (void)setAge:(int)age
{
}
//- (int)age
//{
//
//}
//- (int)age
//{
// return 10;
//}
@end
猫类
@interface Cat : NSObject
{
//int _age;
//int age;
}
@property int age;
@end
@implementation Cat
// 默认会访问age这个成员变量,如果没有age,就会自动生成@private类型的age变量
@synthesize age;
@end
时间: 2024-10-11 23:24:36