zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    二分图最大匹配的König定理及其证明
    HDOJ 2389 Rain on your Parade
    HDOJ 1083 Courses
    HDOJ 2063 过山车
    POJ 1469 COURSES
    UESTC 1817 Complete Building the Houses
    POJ 3464 ACM Computer Factory
    POJ 1459 Power Network
    HDOJ 1532 Drainage Ditches
    HDU 1017 A Mathematical Curiosity
  • 原文地址:https://www.cnblogs.com/jin-wen-xin/p/4667421.html
Copyright © 2011-2022 走看看