自定义构造方法

来源:互联网 发布:重装mac os x系统 编辑:程序博客网 时间:2024/05/13 06:51

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;

}

0 0
原创粉丝点击