类class
Object-C是一种面向对象的语言,但是Object-C的类的定义分为两部分,一部分是接口@interface 部分,另外一部分是 实现@implementation 部分,接口部分个人感觉跟C的头文件的作用类似,主要定义了一些类的成员和方法的原型,而实现部分则是对这些接口中声明的具体实现。
格式
@interface 的格式为 @interface 类名 : 基类
{
成员变量列表
}
方法原形列表
@end
@interface 类名 : 基类
{
成员变量列表
}
方法原形列表
@end
@implementation 类名
类型 函数名:参数列表
-(返回值类型)方法名:参数列表
{
方法体;
}
@end
@implementation 类名
类型 函数名:参数列表
-(返回值类型)方法名:参数列表
{
方法体;
}
@end
Object-C的函数格式
-(返回值类型)方法名:参数列表
{
方法体;
}
注意:
Object-C 的类方法由 - 开始(如果以 + 开始,则表示该方法必须用类名调用,类似于PHP/java/C++/C#的静态函数)
例子:
//
// Test.h
// ObjectC_02
// Autor:DRAGON
// Created by 5016 on 13-11-13.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Test : NSObject
{
NSString *_name;
}
-(void)print;
-(void)test:(int) score;
@property int age;//自动生成getter和setter
@end
//
// Test.m
// ObjectC_02
// Autor:DRAGON
// Created by 5016 on 13-11-13.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import "Test.h"
@implementation Test
@synthesize age;//自动生成getter和setter
/*
*方法:print
*功能:打印一些数据
*/
-(void)print
{
static int i = 0;
NSLog(@"%d",i);
i++;
NSString *n = @"dragon";
_name = n;
NSLog(@"我的名字是%@",_name);
age = 23;
NSLog(@"今年%d岁",age);
}
/*
*方法:test
*功能:打印出成绩的等级
*/
-(void) test:(int) score
{
if(score>=0 && score<60)
{
NSLog(@"不及格");
}
else if(score>=60 && score<70)
{
NSLog(@"不及格");
}
else if(score>=70 && score<80)
{
NSLog(@"中等");
}
else if(score>=80 && score<90)
{
NSLog(@"良好");
}
else if(score>=90 && score<=100)
{
NSLog(@"优秀");
}
else
{
NSLog(@"错误");
}
}
@end
//
// main.m
// ObjectC_02
//
// Created by 5016 on 13-11-13.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Test.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {//自动释放内存
Test *test = [[Test alloc]init];//实例化对象
[test print];//调用无参数函数
Test *test1 = [[Test alloc]init];//实例化对象
[test1 print];//调用无参数函数
[test1 test:95];//调用有参数函数
}
return 0;
}