第一个Objective-C 程序

在win7上面安装了虚拟机,然后安装了MacOSX10.8,下载xcode4.6,进行学习iphone。

由于我长时间从事Java开发,开始看完了《Objective-C基础教程》,模模糊糊不知道,感觉到OC的语法有些奇怪、啰嗦,但是真心想学习iphone开发。于是从网络上找各种资料学习,第一次看到了传智的一个视频,写了一个OC的一个demo,并且进行了代码的详细的解读,分享出来,希望能给和我类似的刚踏入IPhone的童鞋以帮助。

1、create new project

2、create Objective-C class创建类

如图选中Cocoa Touch然后选中 Objective-C class

创建一个Student类的同时,会生成两个文件

Student.m :实体类

Student.h  :接口头文件

3、写接口文件Student.h

   接口主要是声明成员变量和方法

  (a)成员变量写在开头的大括号{ }中

  (b)方法声明:静态方法在 开头用减号 -  ;动态方法用加号 +

  (c)在接口中声明的方法都是公共方法,即在java中用public声明的方法

  (d)类型要写在小括号中( )

  (e)多参数方法的声明,有几个冒号:就有几个参数

代码以及解读如下:

//  声明成员变量 和方法
#import <Foundation/Foundation.h>
@interface Student : NSObject {
   //成员变量定义在这个{}中
    int age;
    int no;
}

// -:动态方法(对象方法) +:静态方法
//OC中所有在.h文件中声明的都是公共方法
//返回值类型用小括号括起来
- (int) getAge;
//一个冒号对应一个参数
-(void) setAge:(int) newAge;

-(void) setAge:(int)newAge andNo:(int)newNo;

// get
-(int) no;

@end

其中声明get的写法有两种,这两种方法相同:

(a)- (int) getAge;

 (b))- (int) age;

4、实现类.m文件

#import "Student.h"
@implementation Student

//age的get方法
- (int)getAge{
    NSLog(@"get age");
    return age;
}

//age的set方法
- (void)setAge:(int)newAge{
    age = newAge;
    NSLog(@"set age");
}

- (int) no{
    NSLog(@"get no");
    return no;
}

- (void)setAge:(int)newAge andNo:(int)newNo{
    age = newAge;
    no = newNo;
}

@end

5、运行

OBjective-C的入口是main方法

这儿有两点需要注意

(a)对象的定义( 分配内存alloc、初始化init )

 (b)方法的调用( [stu2 setAge:20 andNo:30]; )

#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
   /**
    @autoreleasepool {
       
        // insert code here...
        NSLog(@"Hello, World!");
        NSLog(@"xiaobao");
       
    }
    **/
    @autoreleasepool {
        //create Student object
       
        // 调用一个静态方法alloc来分配内存
        //暂时把id当初任何对象
        Student* stu = [Student alloc];


        //调用init方法进行初始化
        stu = [stu init];
            
        [stu setAge:15];
        int age = [stu getAge];
        NSLog(@"age is %i",age);
       
        NSLog(@"--more param of method test--");


        Student* stu2 = [[Student alloc]init];

        //多参数方法的调用
        [stu2 setAge:20 andNo:30];


        int no2 = [stu2 no];
        int age2 = [stu2 getAge];
        NSLog(@"age is %i  and no is %i",age2, no2);
                
        //释放对象release,只能释放一次
        [stu release];
       
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值