ios中,自定义构造方法
Student.h
#improt<Foundation/Foundation.h>
@interface Student:Object{
int _age;
}
-(void)setAge:(int)age;
-(int)age;
@end
Student.m
#import "Student.h"
@implement Student
-(void)setAge:(int)age{
_age = age;
}
-(void)age{
return age;
}
@end
在main文件中,只需要实例化它就可以进行使用了
//核心
Student *student = [[Student all]init];//为其分配内存也可以说是实例化
student.age = 12;
以上是在外部文件进行自定义函数
在文件内部进行函数自定义:
调用:
[self initWithTitle:@"Hello World" initWithAuthor:@"Lin" initWithAge:10]
//方法体
-(instancetype)initWithTitle:(NSString*)title initWithAuthor:(NSString*)author initWithAge:(NSInteger*)age{
self.title = title;
self.author = author;
self.age = age;
}
跟JAVA 的不同点:
在java中写个构造方法(函数)直接写就行了
public setAge( int age){
return age;
}