zoukankan      html  css  js  c++  java
  • Objectivec 使用构造函数来初始化函数并调用函数的方法

    Objective-c 使用构造函数来初始化函数并调用函数

    在objective-c中我们与使用很多其他的oop语言一样,可以使用构造函数,他是在创建对象的时候用来初始化对象数据的一种特殊的方法。构造函数可以使用任何方式命名,但是通常,将他们命名为Init。构造方法返回对象的一个指针,我们可以通过调用超类的init方法来获取这个指针(超类是当前的类所派生自的类,也就是当前类的父类,这里通常是NSObject类);

    参考代码:

    -(Container * ) myInit(int)n

    {

       self = [super init];

       if(self)

      {

             [self  setNumber:n];

       }

        return selef;

    }

    在代码中,当我们创建对象的时候,就可以把值传递给构造方法。例如,如下面的代码把对象中的数据初始化为:3

    Container* obj = [[Container new] myInit:3];

    下面是一个完整的例子的参考代码:

    #import <Foundation/Foundation.h>

    #import "student.h"

    @interface  myobj:NSObject

    {

        int number;

    }

    -(void) setNumber:(int)Num:(int) Num2;

    -(void) outP;

    -(myobj*) myinit:(int)Num:(int)Num2;

    @end

    @implementation myobj

    {

    }

    -(myobj*) myinit:(int)Num:(int)Num2

    {

        self =[super init];// 这里的超类的Init方法的名称是不能改变的

        if (self) {

            [self setNumber:Num:Num2];

        }

        return self;

    }

    -(void) setNumber:(int)Num:(int)Num2{

        number = Num+Num2;

    }

    -(void) outP{

        printf("this is the number you put in =%i",number);

    }

    @end

    int main (int argc, const char * argv[]) {

        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

        myobj* obj = [[myobj new] myinit:10:20];

        [obj outP];

        [pool drain];

        return 0;

    }

    在Console窗口中的运行结果如下所示:

    run

    [Switching to process 643]

    Running…

    this is the number you put in =30

    Debugger stopped.

    Program exited with status value:0.

  • 相关阅读:
    react native 学习资料整理
    yii cookie ,session 操作
    react native 的js 文件从哪里获取
    react native与现有的应用程序集成
    ubuntu 12.04 react-native 安装
    html ul li的学习
    CAGradientLayer的一些属性解析
    ubuntu 安装 swoole 和mac 安装swoole 扩展
    iOS React-Native入门指南之HelloWorld
    实现微信浏览器内打开App Store链接(已被和谐,失效了)
  • 原文地址:https://www.cnblogs.com/xingchen/p/2057756.html
Copyright © 2011-2022 走看看