Objective-C簡稱OC,是一款可以開發Mac OS X平台和iOS平台應用程序的開發語言,目前最新的swift語言也可以開發以上兩平台的應用。
OC是面對對象的語言(OC面對對象語言特性請看之前的博客--->也可以點我!<---),在OC代碼可以混入C語言代碼,甚至是C++代碼,也可以和swift進行混編。
好了,簡介就說這么多>_<
先來個小問題:為什么OC要使用import引入頭文件,import和include的區別?
include 和 import 都是引入頭文件
import引入的頭文件,可以防止重復包含
include它是使用預處理指令防止重復包含,如果沒有寫預處理指令,則無法防止重復包含問題
還記得怎么使用預處理指令防止重復包含嘛
#ifndef Zhy #define Zhy // 函數的聲明 void test(); #endif
使用NSLog輸出自帶換行
NSLog(@"Hello World!");
OC中相對C語言多了一個BOOL類型用來保存邏輯值,YES(真 1) NO(假 0)
OC中的異常捕捉機制
@try { // 有可能會出錯的代碼 <#Code that can potentially throw an exception#> } @catch (NSException *exception) { // 錯誤的處理方法 <#Handle an exception thrown in the @try block#> NSLog(@" %@ ",exception); // 打印出錯誤的信息 } @finally { // 無論是否有錯都會執行 <#Code that gets executed whether or not an exception is thrown#> }
OC中類的創建以及在哪里定義成員變量,類方法和對象方法的聲明和實現
// 人這個類的聲明 @interface Person : NSObject { // 成員變量 NSString *_name; int _age; } // 對象方法的聲明 - (void)duixiangfangfa; // 類方法的聲明 + (void)leifangfa; @end // 人這個類的實現 @implementation Person // 對象方法的實現 - (void)duixiangfangfa { NSLog(@"這是對象方法的實現"); } // 類方法的實現 + (void)leifangfa { NSLog(@"這是類方法的實現"); } @end
說一下創建對象的語句
Person *p = [Person new];
[Person new] 做了三件事情
申請內存空間
給實例變量初始化
返回空間的首地址
小問題:申請的空間在內存的哪個區?
new 的時候申請的空間在內存的堆區(程序動態分配的內存空間)
實例變量保存在堆區,指針p保存在棧區,對象方法保存在代碼區
堆區有一個_isa指針指向代碼區,當對象要調用方法時,首先找p對應的堆區的空間,然后找到 _isa指針,再找到_isa指向的代碼區的空間,然后到該空間中找 方法
設計一個”學生“類
1> 成員變量
* 姓名
* 生日
1 #import <Foundation/Foundation.h> 2 // 日期的結構體 3 typedef struct { 4 5 // 年 6 int year; 7 // 月 8 int month; 9 // 日 10 int day; 11 12 }MyDate; 13 14 // Student類的聲明 15 @interface Student : NSObject 16 { 17 @public 18 // 學生姓名 19 NSString *_name; 20 21 // 學生生日 22 MyDate _birthday; // 結構體變量 23 } 24 25 @end 26 27 28 // Student類的實現 29 @implementation Student 30 31 @end 32 33 34 int main(int argc, const char * argv[]) { 35 @autoreleasepool { 36 37 Student *stu = [Student new]; 38 stu->_name = @"阿衰"; 39 40 //第一種方法 41 stu->_birthday =(MyDate){1983,12,12}; 42 //NSLog(@"%d,%d,%d",stu->_birthday.year,stu->_birthday.month,stu->_birthday.day); 43 44 //第二種方法:定義一個結構體變量 45 MyDate d1 = {1981,11,11}; //定義結構體變量的同時進行初始化 46 stu->_birthday = d1; 47 48 //第三種方法,逐個賦值 49 stu->_birthday.year = 2014; 50 stu->_birthday.month = 12; 51 stu->_birthday.day = 11; 52 53 NSLog(@"%d,%d,%d",stu->_birthday.year,stu->_birthday.month,stu->_birthday.day); 54 } 55 return 0; 56 }
這里主要說明的是調用結構體時的方法
NSString類的用法
NSString是OC中字符串處理的類
NSString *s = @"zzzzzzzzzzzzzz "; NSString *s1 = [NSString stringWithFormat:@"%d",i];
NSString字符串的長度
NSString *s1 = @"zzz"; NSUInteger len = [s1 length]; // 3 // 中文字符在NSString中也占1個字節
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。