Obj-C 學習的一些基礎語法

//The first OC Program
#import <Fundation/Function.h>
int main(int arg, const char args[])
{
	NSAutoreleasePool* pool = [[NSAutorelease alloc] init ];
	NSLog(@"Hello World");
	[pool drain];
	return (0);
}

//Second Test
#import <Fundation/Function.h>
int main(int arg, const char args[])
{
	NSAutoreleasePool* pool = [[NSAutorelease alloc] init ];
	int x = 50, y = 40;
	int sum = x + y;
	NSLog(@"The sum of x and y is %d ", sum);   

	[pool drain];
	return (0);
}
// Obj-C 中的BOOL 
// Obj-C 中的BOOL變量不一樣於其餘語言(好比C/C++, Java),BOOL 的值只有YES和NO,
// 原理上BOOL 變量也是用8位二進制數表示。若是把一個整數賦值給布爾類型,在C++中的不等於0的都是真(true),而Obj-C中
// 變量要看8位二進制數的最低位,最低位爲0則是NO,最低位爲1則是YES

//間接
#import <Fundation/Funtion.h>

int main(int arg, const char args[])
{
	const char* words[4] = {"x1", "x2", "x3", "x4"};// 每次須要改變這些字符串時,都須要改動源代碼
	int i = 0;
	int wordcounts = 4;
	for(; i < wordcounts; ++i)
	{
		NSLog(@"The %s  word's length is %d ", words[i], strlen(words[i]));
	}
	return (0);
}
//改成文件讀取
#import <Fundation/Funtion.h>

int main(int arg, const char args[])
{
	FILE* pFile = fopen("/temp/words.txt","r");   //字符串存於文件中
	char words[100];
	while(fgets(words, 100, pFile))
	{
		words[strlen(words)-1] = '\0';
		NSLog(@"The %s  word's length is %d ", words, strlen(words[i]));
	}

	fclose(pFile);
	return (0);
}


//oop
//面向對象編程大師 Bertrand Meyer 的開放/關閉原則(open/closed principle),即軟件實體應該對擴展開放,對修改關閉。
@interface NSCircle:NSObject
{
	shapeType fillShape;
	colorType fillColor;
}
-(void) setShape: (shapeType) shape;
-(void) setColor: (colorType) color;
-(void) draw;
@end

@implementation NSCircle  //實現方法沒必要按順序,也能夠有一些類中沒有聲明的方法,類中沒有聲明的方法在@implementation中算做私有方法
							//但 並非真正的私有方法! Objective-C 中並無真正的私有方法,這只是Objective-C的反作用
-(void) setShape:(shapeType) shape // 這裏注意形參與@interface中的成員變量重名時會隱藏成員變量
{
	fillShape = shape;
}
-(void) setColor: (colorType) color
{
	fillColor = color;
}
-(void) draw
{
	NSLog(@"The shape is %@ and the color is %@", fillShape, fillColor); //實際上省略了self,   %@是調用了類的description方法
}
@end

//inherit  繼承
@interface Shape
{
	shapeType fillShape;
	colorType  fillColor; 
}
-(void) setShape: (shapeType) shape;
-(void) setColor: (colorType) color;
-(void) draw;
@end

@interface Circle : Shape// 子類能夠共用父類的成員變量,只需重寫相應的方法便可
@end

@interface Rectanle : Shape
@end

@implementation Shape
-(void) setShape: (shapeType) shape  //會複製傳入參數的值,若是參數是指針,則複製指針的值,傳入一個指針的副本(實際上是變量自己,只是指針地址被複制)
{
	fillShape = shape;
}
-(void) setColor: (colorType) color
{
	fillColor = color;
}
-(void) draw
{
	NSLog(@"The shape is %@ and the color is %@")
}
@end

// Obj-C中的init方法 
@interface MyClass
-(id) init
{
	if (self = [super init])
	{
		// do something
	}
}
MyClass* pMyClass1 = [[MyClass alloc] init];
MyClass* pMyClass2 = [MyClass new];
// 一般setter 方法是set+變量名的首字母大寫
//getter方法的方法名與變量名稱相同~~~~~~get這個詞在Cocoa中有特殊的含義,存取方法中千萬不要加入get前綴
// 在Cocoa中,get 出如今方法名裏面時,一般表示這個方法會經過你傳入的(指針參數)來返回數值

//合成存取方法:(調用時的命名規則不變)
//1. 在類的接口部分,在全部的屬性前面@property
//2. 在類的實現部分,@synthesize (name = newName)
// 其中括號中的參數可選。使用可選的規則時,setter和getter方法不變,而類的實例變量爲newName

// 點語法的使用:
// (.)在 「=」 左邊,表示調用了setter
// (.)在 「=」 右邊,表示調用了getter 
// 例如: self.name = nil; 是調用參數爲nil的setter方法,該方法先釋放name所佔內存,再置其值爲nil

//Obj-C中全部對象間的交互都是經過指針來完成的

//不要再description方法中打印self,由於這樣會致使死循環,由於打印self自己又一次調用了description方法。
NSRange:用來表示相關事物的範圍
typedef _NSRange
{
unsigned int location;
unsigned int length;
} NSRange;
例如:"I like apple." apple 能夠用location爲8,length爲5表示。
location未被賦值時,可能爲NSNotFound.
@ NSRange range;
  range.location = 5;
  range.length = 9;

@NSRange range = {5, 9}; // C語言風格

@NSRange range = NSMakeRange(5, 9);  // Obj-C風格
Obj-C風格的好處是能夠在任何的函數調用中使用
[anObject function: NsSMakeRange(5, 9)];


typedef struct _NSPoint     //NSMakePoint()
{
float x;
float y;
}NSPiont;
表示笛卡爾平面中的一個點

typedef struct _NSSize    //NSMakeSize()
{ 
float width;
float height;
}NSSize; 
數據的寬度和長度

typedef struct _NSRect   //NSMakeRect()
{ 
NSPoint origin;
NSSize  size;
}NSRect;
// 用數據結構是爲了提高性能,由於GUI程序會用到不少臨時的點,這些數據若是採用
//類來表示就要用動態分配,會犧牲性能。


NSString:處理字符串的類
//NSString 類不可變,一旦建立後不能改變它,例如不能添加和刪除字符
//NSString 有一個子類NSMultableString, 是能夠改變的。

NSString 的stringWithFormat的類方法原型以下:

+(id) stringWithFormat: (NSString* ) format, ...;
NSString* string = [NSString stringWithFormat:
                   @"I have %d apples", 5] ;
//」+「 表明這個方法是類方法,一般用於建立新的實例時調用,建立新對象的類方法稱
//爲工廠方法, 類方法也能夠用來訪問全局變量
//例如AppKit中的NSColor類就有redColor和blueColor方法。

NSColor* color = [NSColor redColor];

//Obj-C中生成一個類的時候,會建立一個表明該類的類對象。類對象中包含
//1.指向超類的指針
//2.指向類方法列表的指針
//3.類名
//4.一個long型數據,爲新建立的類實例對象指定大小(以字節爲單位)


-(unsigned int) length; // 能夠準確的計算標準字符串和國際化字符編碼,
//如俄文,法文等~

NSString* string = [NSString stringWithFormat:"I like apple."];
int length = [string length];

-(BOOL) isEqualToString: (NSString*) string;
NSString* string1 = @"Hello";
NSString* string2 ;
string2 = [NSString stringWithFormat:"Hello"];
if ([string1 isEqualToString:string2])  
//不能簡單的比較指針值,比較指針值時實際上是判斷兩個string是否指向同一個字符串
{
    NSLog(@"They are the same string!");
}

// 區分大小寫的比較
-(NSComparisonResult)compare:(NSString*) string;
typedef enum _NSComparisonResult //一個枚舉變量
{
    NSOrderedAscending = -1;  //左側的值小於右側,即字母表中第一個字符串要靠前
    NSOrderedSame;
    NSOrderedDescending;
    NSComparisonResult;
}
[@"a" compare: @"b"];  // 返回NSOrderedAscending;

//不區分大小寫的比較
-(NSComparisonResult)compare:(NSString*) string 
                     options:(unsigned) mask; 
//options的參數是一個位掩碼,可使用|(位或)來結合使用
//經常使用的位掩碼有:
NSCaseInsensitiveSearch //不區分大小寫
NSLiteralSearch        //徹底比較,區分大小寫
NSNumericSearch       //比較字符串的字符個數,而不是字符串的值

//忽略大小寫且按字符串的字符數量排序
if(NSOrderSame == [string1 compare: string2
                           options:NSCaseInsensitiveSearch 
                                   | NSNumericSearch])
{
NSLog(@"");
}

//判斷字符串開頭前綴和結尾後綴的方法
-(BOOL) hasPrefix: (NSString*) string; //是否以string做爲前綴開頭
-(BOOL) hasSuffix: (NSString*) string; //是否以string做爲後綴結尾

NSString* string = @"abc.mov";
if([string hasPrefix:@"abc"]){NSLog();}
if([string hasSuffix:@".mov"]){NSLog();}

//判斷某個字符串中是否包含另外一個另外一個字符串
-(NSRange)rangeOfString: (NSString*) string;

NSRange range;  //返回一個range.start 和 一個 range.length
range = [@"fsfghdhfhg" rangeOfString: @"abc"];


//頭文件中一般存放: 1. 類的@interface指令
                 2. 公共的struct定義
                 3. enum常量
                 4. #defines 和取 extern 全局變量

// 實現文件中存放: 1. 類的實現@implementation
                 2. 全局變量的定義
                 3. 私有struct

//#import <>  用來導入系統頭文件  
//不會重複導入

//#import 「」 用來導入自定義頭文件

//@class 是用來防止多重依賴時修改一個文件致使重編譯的問題。這樣只是聲明一個類便可,而不須要了解類中有多少個實例變量。
//也能夠用@class 防止循環引用的問題。
// 在繼承關係鏈中,@class不能成功,由於繼承的類須要知道父類的所有信息,須要使用#import「X.h」文件

Cocoa 框架包含兩個子框架:

 1.Foundation Kit    //開發文檔位置:/Developer/ADC Reference Library/documentation/index.html  
 2. Application Kit
相關文章
相關標籤/搜索