黑马程序员技术交流社区

标题: 创建一个简单的OC类 [打印本页]

作者: chingwei2011    时间: 2015-10-11 16:51
标题: 创建一个简单的OC类
main.m 文件
  1. #import <Foundation/Foundation.h>
  2. #import "Person.h" //导入类的.h文件
  3. int main(int argc, const char * argv[]) {
  4.     @autoreleasepool {
  5.       
  6.         Person *person;//nil
  7.         person =[[Person alloc]init];
  8.         NSLog(@"Person:%p",person);// Person:0x100406140
  9.    
  10.         //创建对象并初始化
  11.         
  12.         // Person *person2 =[[[Person alloc]init]initWithAge:30 identify:358967822];
  13.         
  14.         Person *person2 =[[Person alloc]initWithAge:30 identify:358967822];//初始化对象,赋值,
  15.         NSLog(@"Age1 : %d",[person2 getAge]);
  16.         int age =28 ;
  17.         [person2 setAge:age];//调用setAge方法,设置年龄
  18.         NSLog(@"Age1 : %d",[person2 getAge]);
  19.         [person2 setAge:++age];
  20.         NSLog(@"Age1 : %d",[person2 getAge]);
  21.         NSLog(@"Person:%p",person2);// Person:0x100406140
  22.         
  23.         
  24.     }
  25.     return 0;
  26. }
复制代码
Person.h 类的创建
  1. #import <Foundation/Foundation.h>

  2. @interface Person : NSObject
  3. {
  4.     int identify;
  5.     int age ;
  6. }
  7. -(id)initWithAge:(int) _age identify:(int) _identify;
  8. -(int)getIdentify;
  9. -(int)getAge;
  10. -(void)setAge:(int)_age;
  11. @end
复制代码
Person.m 类的声明部分
  1. #import "Person.h"

  2. @implementation Person

  3. -(id) init //隐藏的init、初始化 没有会调用父类的
  4. {
  5.     if(self = [super init ]){
  6.         NSLog(@"super init");
  7.     }
  8.     return self;
  9.    
  10. }
  11. -(id)initWithAge:(int) _age identify:(int) _identify{
  12.     if(self=[super init])//父类初始化成功 self、是子类
  13.     {
  14.         age=_age;
  15.         identify =_identify;
  16.         
  17.     }
  18.     return self;//返回ID、类型
  19. }

  20. -(int)getIdentify{
  21.     return identify;
  22. }

  23. -(int)getAge{
  24.     return age;
  25. }

  26. -(void)setAge:(int)_age{
  27.     age=_age;
  28. }

  29. @end
复制代码

代码亲测可用,同学可以仔细阅读代码,能了解到类的基本的概念和运行的方式。
代码是在看视频的时候边看边敲的。希望能帮助到大家。





作者: chingwei2011    时间: 2015-10-16 08:32
自己支持一下。
作者: L503254118    时间: 2015-10-16 09:30
挺好的,楼主加油




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2