標籤:
一、Objective-C語言的特點
1、支援C語言文法,是一個高效的程式設計語言。
2、作為C語言物件導向的擴充,支援完整的物件導向的編程特性。
3、簡潔而優雅的編程風格使得編寫程式與閱讀代碼都變得格外清晰。
4、相容性好,可以在同一個項目中同時使用OC與C++,也可以在項目中匯入由C、C++等語言編寫的庫檔案。
如何學好這門語言?
OC語言文法預覽:
C語言實現檔案.c C++實現檔案.cpp OC實現檔案.m OC&&C++實現檔案.mm 標頭檔都是.h
類的定義:
@interface SimpleClass:NSObject
@end
類的屬性聲明:
@interface Person:NSObject
@property NSString *firstName;
@property NSString *lastName;
@end;
@property NSNumber *yearOfBirth;
@property int yearOfBirth;
@property (readonly) NSString *firstName;
減號方法(普通方法又稱對象方法或執行個體方法)申明
加號方法(類方法,又稱靜態方法)申明
類的實現:
#import "XYZPerson.h"
@implementtation XYZPerson
@end
二、
OOP(Objective Oriented Programming)--物件導向編程
OOA(Object-Oriented Analysis)--物件導向分析
OOD(Object Oriented Design)--物件導向設計
三、
C++:1983--貝爾實驗室。Simula 67 複雜,靜態
Objective--C: 1988--喬布斯NextStep。Smaltalk 簡單,動態
四、類和對象的基本概念
1、建立類、得到對象。-->類的執行個體化。
1 //執行個體化對象 2 /* 3 [類名 方法名] 4 [對象名 方法名] 5 alloc - 為對象分配記憶體空間 6 init - 進行初始化操作 7 */ 8 People *p1 = [[People alloc] init];//推薦 9 People *p2 = [People new];10 11 NSLog(@"%p", p1);12 NSLog(@"%p", p2);
2、成員變數的聲明和使用。屬性的聲明和使用
1 #import <Foundation/Foundation.h> 2 //類內使用成員變數。類外使用成員屬性。 3 @interface People : NSObject 4 //聲明成員變數 5 { 6 @public 7 NSString *_peopleName; 8 int _peopleAge; 9 int _peopleSex;10 }11 //屬性為了讓類外可以訪問成員變數12 //屬性就是成員變數的外部介面13 @property (nonatomic, strong) NSString *peopleName;//聲明屬性14 15 @end
1 #import "People.h" 2 3 @implementation People 4 5 - (instancetype) init 6 { 7 if (self = [super init]) 8 { 9 //類內調用成員變數而不是屬性,屬性是給類外使用的。10 self.peopleName = @"張三";11 }12 return self;13 }14 15 @end
後記:練習的原始碼:
1 #import <Foundation/Foundation.h> 2 #import "People.h" 3 4 int main(int argc, const char * argv[]) 5 { 6 @autoreleasepool 7 { 8 //調用方法使用[] 9 People *p1 = [[People alloc] init];10 int a = [p1 report];11 NSLog(@"%d", a);12 // [People report1];13 int a1 = [p1 showWithA:10];14 NSLog(@"%d", a1);15 int a2 = [p1 showWithA:10 andB:20];16 NSLog(@"%d", a2);17 }18 return 0;19 }20 21 #import <Foundation/Foundation.h>22 /*23 1、 - 代表對象方法就(執行個體方法):用對象名來調用 +代表類方法:用類名來調用24 加號方法和減號方法可以互相調用,當然需要類名和執行個體化變數,加號方法不能調用成員變數。25 2、- (int) 傳回值類型26 3、:(int)x - :代表有參數,(int)代表參數類型,a代表參數名27 4、函數名(方法名) - 去掉方法類型,去掉參數類型、去掉參數名,剩下的就是方法名28 */29 @interface People : NSObject30 31 - (int)report;32 + (void)report1;33 34 - (int)showWithA:(int)a;35 //showWithA: andB:(函數名/方法名)36 - (int)showWithA:(int)a andB:(int)b;37 38 39 @end40 41 #import "People.h"42 43 @implementation People44 45 {46 NSString *_peopleName;47 }48 49 static NSString *_peopleName1;50 51 - (int)report52 {53 NSLog(@"report");54 [People report1];55 _peopleName = @"123";56 return 20;57 58 }59 60 + (void)report161 {62 NSLog(@"report1");63 // [[People alloc] report];//死迴圈64 _peopleName1 = @"張三";65 66 }67 68 - (int)showWithA:(int)a69 {70 return a;71 }72 - (int)showWithA:(int)a andB:(int)b73 {74 return a + b;75 }76 77 78 @end
Objective--C隨筆2016年8月7日