1. Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
//成員變量
NSString *name;
int age;
}
//初始化方法 必須init開頭 類似Java構造函數
-(id)initMy;
-(void)setInfo:(NSString *) name:(int) age;
-(void)getInfo;
//+號表示這個方法爲靜態方法
+(void) addCount;
@end
2. Student.m
#import "Student.h"
//static靜態變量 只初始化一次 再賦值無效
static int count = 100;
@implementation Student
-(id)initMy{
self =[super init];
if(self){
[self setInfo:@"哈哈" :26];
}
return self;
}
//-方法 必須通過本類的對象纔可以使用
-(void) setInfo:(NSString *)mName :(int)mAge{
name=mName;
age=mAge;
}
-(void) getInfo{
NSLog(@"姓名:%@",name);
NSLog(@"年齡:%d",age);
}
//+號表示這個方法爲靜態方法
+(void)addCount{
count++;
NSLog(@"Count=%d",count);
}
@end
3. 對象調用
#import "ViewController.h"
#import "Student.h"
@interface ViewController (){
Student *student;
}
@end
@implementation ViewController
//程序啓動界面顯示之前會調用這個方法
//所以將語法代碼添加在這裏
- (void)viewDidLoad {
[super viewDidLoad];
//創建對象
student=[[Student alloc] initMy];
//調用方法
[student getInfo];
//靜態方法直接用類名調用
[Student addCount];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end