1.7 给自定义类平添实例方法
1.7 给自定义类添加实例方法
1、问题
在Objective-C中,你可以发送消息给类或对象,以完成一个任务。如果你想要一个对象能够响应消息,就需要编写实例方法。
2、解决方案
要添加实例方法,就需要在头文件中添加forward declaration。实例方法以-开头,还要有一个返回类型,如(void),之后是参数描述符,数据类型,以及参数名。之后要到实现文件中实现该方法。
3、原理
声明:
-(void)writeOutThisCarsState;
实现:
-(void)writeOutThisCarsState{
NSLog(@"This car is a %@", self.name);
}
4、调用代码
Car *newCar = [[Car alloc] init];
newCar.name = @"My New Car";
[newCar writeOutThisCarsState];