本文是觀看了 @M了個J 視頻 整理的一些學習資料 在這裏感謝大神[(@M了個J)
大神博客鏈接的地址爲 http://www.cnblogs.com/mjios/] 在這裏謝謝大神,同時也謝謝那些無私奉獻知識的人 如果說我比別人看得更遠些,那是因爲我站在了巨人的肩上
--牛頓
類的聲明 (set、get方法的實現)
OC中類分爲2個文件
.h 類的聲明文件,用於聲明變量、函數(方法)
.m 類的實現文件,用於實現.h中的函數(方法)
類的聲明使用關鍵字@interface、@end
類的實現使用關鍵字@implementation、@end
.h文件寫法
#import <Foundation/Foundation.h> / /導入常用的頭文件 其中包含NSObject基類的頭文件 Object-c中使用#import 導入頭文件可以防止頭文件被重複引用
@interface Student : NSObject { //一定要寫清楚繼承誰,不可省略
int age;
}
//在這裏聲明的方法都是公共的
// -代表動態方法(獲取某一個對象屬性的方法) + 代表靜態方法
//age 的get方法
- (int) getAge;
//age 的set方法
- (void)setAge :(int)newAge; //在寫方法時 : 一個:對應一個類型,變量的類型用()
@end
.m文件寫法
#import "Student.h"
@implementation Student
- getAge{
return age; //因爲我們有#import "Student.h"
}
-(void)setAge:(int)newAge{
age = newAge;
}
@end
創建、使用對象
//創建一個Student對象
//1.調用一個靜態方法alloc來分配內存
[Student alloc] //用類名去調用的方法,可以知道alloc是靜態的方法 可以按住command鍵 查看alloc方法 可以知道alloc方法返回一個id類型的對象
Student * stu = [Student alloc] //OC中所有的對象的聲明都要加* 我們把返回的id類型給 Student類型的stu
//2.調用一個動態方法init進行初始化 第一步Student *>
stu = [stu init];
//1 2可以連起來使用
Student * stu = [ [Student alloc] init ]; //alloc init 方法都是NSObject的方法
[stu setAge:100]; //一個:對應一個參數
int age =[stu getAge];
NSLog(@"age is %i",age);
//釋放對象
[stu release];
//在OC中 建議我們把get方法名寫成變量名把我們寫的 - (int) getAge;改稱- (int)age; 調用時 [stu age]
-(void)setAge:(int)newAge andNo:(int)newNo; //帶有兩個參數的set方法
調用時 [stu setAge:17 andNo:1];