/*
Objective-c - @property的参数strong与weak
1,如果使用strong来修饰类的属性,代表@property生成的私有属性是一个强类型的.
2,如果使用weak来修饰类的属性,代表@property生成的私有属性是一个弱类型的.
注意:ARC机制下,setter方法的实现,不需要做别的什么事情,直接复制就可以,所以MRC下的retain在ARC无法使用.
总结:在ARC机制下,如果属性的类型是oc对象类型的,绝大多数情况下使用参数strong,如果属性的类型是非oc对象类型的,绝大多数情况下使用assign,也就是相当于把MRC下的retain换成了strong.
*/
#import
#pragma mark -
#pragma mark 车类的声明
@interface YYCar : NSObject
@property(nonatomic,strong)NSString *brand;
@property(nonatomic,assign)int speed;
//行驶的方法
- (void)run;
//自定义构造方法
- (instancetype)initWithBrand:(NSString *)brand;
- (instancetype)initWithBrand:(NSString *)brand andSpeed:(int)speed;
+ (instancetype)carWithBrand:(NSString *)brand;
+ (instancetype)carWithBrand:(NSString *)brand andSpeed:(int)speed;
@end
#pragma mark -
#pragma mark 车类的实现
@implementation YYCar
//行驶的方法
- (void)run
{
NSLog(@"时速%d的%@在行驶!", _speed, _brand);
}
//自定义构造方法
- (instancetype)initWithBrand:(NSString *)brand
{
if(self = [super init])
{
self.brand = brand;
}
return self;
}
- (instancetype)initWithBrand:(NSString *)brand andSpeed:(int)speed
{
if(self = [super init])
{
self.brand = brand;
self.speed = speed;
}
return self;
}
+ (instancetype)carWithBrand:(NSString *)brand
{
return [[self alloc]initWithBrand:brand];
}
+ (instancetype)carWithBrand:(NSString *)brand andSpeed:(int)speed
{
return [[self alloc]initWithBrand:brand andSpeed:speed];
}
@end
#pragma mark -
#pragma mark 人类的声明
@interface YYPerson : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic,strong)YYCar *car;
//驾驶的方法
- (void)drive:(YYCar *)car;
//自定义构造方法
- (instancetype)initWithName:(NSString *)name;
- (instancetype)initWithName:(NSString *)name andCar:(YYCar *)car;
+ (instancetype)personWithName:(NSString *)name;
+ (instancetype)personWithName:(NSString *)name andCar:(YYCar *)car;
@end
#pragma mark -
#pragma mark 人类的实现
@implementation YYPerson
//驾驶的方法
- (void)drive:(YYCar *)car;
{
NSLog(@"%@驾驶时速%d的%@去上学!", _name, car.speed, car.brand);
[_car run];
}
//自定义构造方法
- (instancetype)initWithName:(NSString *)name
{
if(self = [super init])
{
self.name = name;
}
return self;
}
- (instancetype)initWithName:(NSString *)name andCar:(YYCar *)car
{
if(self = [super init])
{
self.name = name;
self.car = car;
}
return self;
}
+ (instancetype)personWithName:(NSString *)name
{
return [[self alloc]initWithName:name];
}
+ (instancetype)personWithName:(NSString *)name andCar:(YYCar *)car
{
return [[self alloc]initWithName:name andCar:car];
}
@end
#pragma mark -
#pragma mark main函数
int main(int argc, const char * argv[]) {
//创建车对象并初始化
YYCar *bz = [YYCar carWithBrand:@"奔驰" andSpeed:120];
//创建人对象并初始化
YYPerson *xiaoming = [YYPerson personWithName:@"小明" andCar:bz];
//调用方法
[xiaoming drive:bz];
return 0;
}