• 【IOS】3. OC 类声明和实现


    .h文件

    @interface NewClassName:ParentClassName

    {

       实例变量;//基本类型和指针类型  不能在这里初始化,系统默认会初始化

    系统初始化遵循:

    实例变量类型  默认值

    Byte      0

    short     0

    int     0

    long  0L

    char    u0000'

    float   0.0F

    double   0.0D

    Boolean   FALSE

    pointer     nil

      ~~~~

    }

    方法的声明;

      ~~~~ 

    - (void) method: (int) arguments;

    - 表示实例方法

    +表示类的方法

    method是方法名 后跟的冒号很关键

    @end

    Example 1:

    @interface Person:NSObject   //NSObject 是所有类的父类

    {

    int identify;

    int age;

    }

    -(id) initWithAge:(int) _age identify: (int) _identify; //方法名 initWithAge:identify:

    -(int) getIdentify;

    -(int) getAge;

    -(void) setAge:(int) _age;

    +(Person *) sharePerson

    @end

    .m文件

    @implementation NewClassName{

    }

    Example 2:

     @implementation Person

    -(id) initWithAge:(int) _age identify: (int) _identify

    {  

      if(self = [super init])

      {

        age=_age;

        identify=_identify;

      }

    }

    方法调用(发送消息)

    [类名 or 对象名 方法名]

    [ClassOrInstance method1:arg1 method2:arg2];多参数的调用

    [[ClassOrInstance method:arg1] otherMethod];消息嵌套

    指针

    NSString *s;

    s=[[NSString alloc] initWithString:@"Hello Iphone"];

    alloc 方法创建了一个NSString类型的对象,在堆区,动态分配内存,并用S指向它。

    对象创建和使用

    对象通过指针来声明  ClassA *object

    对象的创建:

    ClassA *cls=[ClassA alloc]; //使用alloc创建一个对象。编译器会分给这个对象一块可用的内存地址。

    cls= [cls init] ;//需要对这个新对象调用 init方法

    NSLog(@"cls %p",person); //打印内存地址

    方法嵌套的形式创建对象 

    Person *person=[[Person alloc] init];

    main

    对象的初始化

    一般初始化的方法名都init开头,并且成功完成初始化后,返回一个动态类型对象(id), 失败的话返回nil。

    @interface C:NSObject

    {

       int a;

       int b;

    }

    @end

  • 相关阅读:
    Windows下git使用代理服务器的设置方法
    SQL backup&restore
    css3 随记
    HTML5 上传图片预览
    jQuery.event.move
    css3 html5 手机设备 列表的弹回和加速移动
    16进制与utf-8
    android 使用现成做get请求
    android 往sd卡中写入文件
    android 遍历控件
  • 原文地址:https://www.cnblogs.com/jin-wen-xin/p/4667421.html
Copyright © 2020-2023  润新知