学前说明:构造函数是在创建给定类型的对象执行的类方法,在java中构造方法名与类是同名.构造方法的作用是为指定累创建
相应的操作对象。Object-c构造函数其实和java的构造函数有很大的相似之处。
以Student类为例:
java:public Student(){ //无参构造函数
}
public Student(int age, int no){ //带有两个参数的构造函数
this.age = age;
this.no = no;
}
Object-c: 声明 .h -(id)init; //无参构造函数,是NSObject 这个父类的方法
.m -(id) init {
return self;
}
.h -(id)initWithAge:(int)age andNo:(int)no; //带有两个参数的构造方法
.m - (id) initWithAge:(int)age andNo:(int)no{
if(self=[super init]){
self.age = age;
self.no = no;
}
return self;
}
两个参数构造方法的使用:
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc , const char * argv[]){
@autorleasepool{
Student *stu = [[Student alloc] initWithAge:10 andNo:5];
NSLog(@"the Student's age is %i and no is %i",stu.age,stu.no);
//此处如果没有复写description方法将会打印出student对象的指针地址 @(相关只是补充)
NSLog(@"the Student is %@",stu);
[stu release];
}
return 0;
}
相关知识补充:
@ 在java中直接通过System.out.println(stu)直接打印对象的形式,系统回自动调用对象的toString方法。
如果toString没有被复写,那么将会打印出对象的hashcode值;在object-c中,以%@的替代符的形式代替对象
,同样系统会调用description方法来将对象的指针地址打印出来。我们可以通过复写description函数来让系统
打印出我们想要的对象说明。
description方法复写:
-(NNString *)description{
NNString *str = [NNString stringWithFormat:@"the Student's age is %i and no is %i",self.age,self.no]; //此处可以省略self引用,直接写成 age ,no;
return str;
}
总结:
感觉object-c代码写起来还挺漂亮的,因为一直做android开发,java代码看习惯了,所以有时候看到其他的语言总觉的怪怪的,其实不然啊,学一门语言只要开始上手了,看起来还蛮舒服的。
---- read the fucking code !
相应的操作对象。Object-c构造函数其实和java的构造函数有很大的相似之处。
以Student类为例:
java:public Student(){ //无参构造函数
}
public Student(int age, int no){ //带有两个参数的构造函数
this.age = age;
this.no = no;
}
Object-c: 声明 .h -(id)init; //无参构造函数,是NSObject 这个父类的方法
.m -(id) init {
return self;
}
.h -(id)initWithAge:(int)age andNo:(int)no; //带有两个参数的构造方法
.m - (id) initWithAge:(int)age andNo:(int)no{
if(self=[super init]){
self.age = age;
self.no = no;
}
return self;
}
两个参数构造方法的使用:
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc , const char * argv[]){
@autorleasepool{
Student *stu = [[Student alloc] initWithAge:10 andNo:5];
NSLog(@"the Student's age is %i and no is %i",stu.age,stu.no);
//此处如果没有复写description方法将会打印出student对象的指针地址 @(相关只是补充)
NSLog(@"the Student is %@",stu);
[stu release];
}
return 0;
}
相关知识补充:
@ 在java中直接通过System.out.println(stu)直接打印对象的形式,系统回自动调用对象的toString方法。
如果toString没有被复写,那么将会打印出对象的hashcode值;在object-c中,以%@的替代符的形式代替对象
,同样系统会调用description方法来将对象的指针地址打印出来。我们可以通过复写description函数来让系统
打印出我们想要的对象说明。
description方法复写:
-(NNString *)description{
NNString *str = [NNString stringWithFormat:@"the Student's age is %i and no is %i",self.age,self.no]; //此处可以省略self引用,直接写成 age ,no;
return str;
}
总结:
感觉object-c代码写起来还挺漂亮的,因为一直做android开发,java代码看习惯了,所以有时候看到其他的语言总觉的怪怪的,其实不然啊,学一门语言只要开始上手了,看起来还蛮舒服的。
---- read the fucking code !
本文介绍了Objective-C中的构造函数,包括无参构造函数和带有参数的构造方法,并通过Student类举例说明。同时,讨论了Objective-C中类似Java的toString方法的description方法,以及如何复写该方法以自定义对象打印内容。
3846

被折叠的 条评论
为什么被折叠?



