`

ios初步学习一些概念及语法的理解

ios 
阅读更多
//定义一个类
#import <Foundation/Foundation.h>

@interface Student : NSObject
{
int _age;
int _no;
}
- (void)setAge:(int)age;
- (void)setNo:(int)no;
- (int)age;
- (int)no;
- (id)initWithAge:(int)age andNo:(int)no;
@end

//类的实现
#import "Student.h"

@implementation Student
//编写构造方法
- (id)initWithAge:(int)age andNo:(int)no{
self = [super init];//调用父类的init方法
self.age = age;
self.no = no;
return self;
}
- (void)setAge:(int)age{
_age=age;
}
- (void)setNo:(int)no{
_no = no;
}
- (int)age{
return _age;
}
- (int)no{
return _no;
}
//重写类对象的description方法,这个方法在 %@ 时候被调用,%@ 表示输出对象
- (NSString *)description{
NSString *str = [NSString stringWithFormat:@"age is %i no is %i",self.age,self.no];
return str;
}
@end

//类的调用
#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
//方法一,第一步调用类的静态方法分配内存,第二步把分配的内存初始化之后给对象stu
Student *stu = [[Student alloc] init];
[stu setNo:10];
//等于stu.age = 10; stu的点方法,其实调用的不是成员变量,而是对应的set方法
[stu setAge:27];
NSLog(@"huang age is %i and no is %i",[stu age],[stu no]);

//方法二,第一步调用类的静态方法分配内存,第二步调用自己的构造方法初始化
Student *stu2 = [[Student alloc] initWithAge:27 andNo:1];
NSLog(@"mei age is %i and no is %i",[stu2 age],[stu2 no]);

NSLog(@"stu is %@",stu);//输出对象,有点像java当中的toString方法
//释放对象的方法怎么出不来呢?
// 在输出对象时候如果不重写Student当中的description方法,那么输出的是stu的内存地址
}
    return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics