黑马程序员技术交流社区
标题:
创建一个简单的OC类
[打印本页]
作者:
chingwei2011
时间:
2015-10-11 16:51
标题:
创建一个简单的OC类
main.m 文件
#import <Foundation/Foundation.h>
#import "Person.h" //导入类的.h文件
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person;//nil
person =[[Person alloc]init];
NSLog(@"Person:%p",person);// Person:0x100406140
//创建对象并初始化
// Person *person2 =[[[Person alloc]init]initWithAge:30 identify:358967822];
Person *person2 =[[Person alloc]initWithAge:30 identify:358967822];//初始化对象,赋值,
NSLog(@"Age1 : %d",[person2 getAge]);
int age =28 ;
[person2 setAge:age];//调用setAge方法,设置年龄
NSLog(@"Age1 : %d",[person2 getAge]);
[person2 setAge:++age];
NSLog(@"Age1 : %d",[person2 getAge]);
NSLog(@"Person:%p",person2);// Person:0x100406140
}
return 0;
}
复制代码
Person.h 类的创建
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int identify;
int age ;
}
-(id)initWithAge:(int) _age identify:(int) _identify;
-(int)getIdentify;
-(int)getAge;
-(void)setAge:(int)_age;
@end
复制代码
Person.m 类的声明部分
#import "Person.h"
@implementation Person
-(id) init //隐藏的init、初始化 没有会调用父类的
{
if(self = [super init ]){
NSLog(@"super init");
}
return self;
}
-(id)initWithAge:(int) _age identify:(int) _identify{
if(self=[super init])//父类初始化成功 self、是子类
{
age=_age;
identify =_identify;
}
return self;//返回ID、类型
}
-(int)getIdentify{
return identify;
}
-(int)getAge{
return age;
}
-(void)setAge:(int)_age{
age=_age;
}
@end
复制代码
代码亲测可用,同学可以仔细阅读代码,能了解到类的基本的概念和运行的方式。
代码是在看视频的时候边看边敲的。希望能帮助到大家。
作者:
chingwei2011
时间:
2015-10-16 08:32
自己支持一下。
作者:
L503254118
时间:
2015-10-16 09:30
挺好的,楼主加油
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2