第三章 字符串
一些有用的數(shù)據(jù)類型: 表示范圍作用的結(jié)構(gòu)體:NSRange: 有三種方式創(chuàng)建新的 NSRange
1、NSRange range; range.location = 17; range.length = 4;
2、NSRange range = {17 ,4}; 3、NSRangerange=NSMakeRange(17,4); (推薦)
表示用來處理幾何圖形的數(shù)據(jù)類型:NSPoint(點坐標)和 NSSize(長度和寬度)還有一個矩形數(shù)據(jù)類
型(由點和大小復合而成)NSRect
Cocoa 提供創(chuàng)建這些數(shù)據(jù)類型方法:NSMakePoint() 、NSMakeSize()和 NAMakeRect()
表示字符串的類 NSString
NSString *heigth =[NSString stringWithFormat: @"Youheigth is %d feet,%d inches", 5,11];
創(chuàng)建的類對象包含了指向超類的指針、 類名和指向類方法的列表的指針。 類對象還包含一lon個g 的數(shù)據(jù), 為新創(chuàng)建的類對象指定大小。
返回字符串中的字符的個數(shù):
unsigned int length = [heigth length]; 返回 Bool 值的字符串比較函數(shù):
- (BOOL) isEqualToString:(NSString *)aString;//比較兩個字符串的內(nèi)容是否相等 還可以使用 compare :方法
-(NSComparisonResult)compare :(NSString *)string;//逐個字符比較 不區(qū)分大小寫的比較:
-(NSComparisonResult)compare :(NSString *)string options:(unsigned)mask; 注意:NSComparisonResult 是一個枚舉值
options 是一個位掩碼,即:
NSCaseInsensitiveSearch:不區(qū)分大小寫
NSLiteralSearch: 進行完全比較,區(qū)分大小寫
NSNumericSearch: 比較字符串的字符個數(shù),而不是字符值
檢查字符串是否以另一個字符串開頭 -(BOOL)hasPrefix : (NSString *)aString;
判斷字符串是否是以另一個字符串結(jié)尾
-(BOOL)hasSuffix : (NSString *)aString; 如果你想知道字符串內(nèi)的某處是否包含其他字符串,使用rangeOfString: 方法
-(NSRange)rangeOfString :(NSString *)aString;
NSString 是不可變的,NSMutableString 是可變的。用方法 stringWithCapacity :來創(chuàng)建
NSMutableString *string = [NSMutableString stringWithCapacity :42];
可以使用 appendString :或 appendFormat : 來附加新字符串:
- (void) appendString :(NSString *)aString;
- (void) appendFormat :(NSString *)format , . . . ;
可以使用deleteCharactersInRange: 方法刪除字符串中的字符
-(void)deleteCharactersInRange: (NSRange)range;
集合家族:
NSArray:用來存儲對象的有序列表(任意類型的對象)
限制: 只能存儲Objective—C 的對象, 不能存儲C 語言的基本數(shù)據(jù)類型 (int、float、enum、struct、 或者NSArray
中的隨機指針) 。同時也不能存儲nil(對象的零值或NULL值)
//創(chuàng)建一個新的 NSArray
NSArray *array =[NSArray arrayWithObjects: @"one",@"two",nil];
//獲得包含的對象個數(shù)
- (unsigned)count;
//獲得特定索引處的對象
- (id)objectAtIndex :(unsigned int)index ;
切分數(shù)組:
使用 componentsSeparatedByString : 來切分 NSArray,
NSString *string = @"oop : ack : bork : greeble : ponies" ;
NSArray *chunks = [string componentsSeparatedByString : @":"];
使用 componentsJoinedByString : 來合并 NSArray 中的元素并創(chuàng)建字符串
string = [chunks componentsJoinedByString :@":-)"] ;
NSArray 是不可變數(shù)組,數(shù)組中包含的對象是可以改變的,但是數(shù)組對象本身是不會改變的。
可變數(shù)組 NSMutableArray 通過類方法 arrayWithCapacity : 來創(chuàng)建可變數(shù)組
+ (id)arrayWithCapacity :(unsigned)numItems ;
NSMutableArray *array = [NSMutableArray arrayWithCapacity : 17];
使用 addObject : 在數(shù)組末尾添加對象 - (void)addObject :(id)anObject
刪除特定索引的對象
- (void)removeObjectAtIndex :(unsigned)index;
注:可變數(shù)組還可以在特定索引處插入對象,替換對象,為數(shù)組排序N,SArray 還提供了大量好用的功能。
枚舉:
NSEnumerator 用來描述這種集合迭代器運算的方法:
要想使用 NSEnumerator,需要通過 objectEnumerator 向數(shù)組請求枚舉器:
- (NSEnumerator *) objectEnumerator;
可以像這樣使用這個方法:
NSEnumerator *enumerator;
enumerator = [array objectEnumerator ];
注:若想從后向前枚舉集合,使用方法reverseobjectEnumerator; 也可以使用。
獲得枚舉器以后,開始 while 循環(huán),每次循環(huán)都向這個枚舉器請求它的nextObject
- (id)nextObject;//返回 nil 表明循環(huán)結(jié)束
注:在枚舉的過程中不能改變數(shù)組容器。
快速枚舉示例:
for(NSString *string in array){ NSLog(@"I found %@", string);
}
數(shù)組排序:
例如:一條記錄就是一條卡片的信息,包括(NSString *name 和 NSString *email)
-(void)sort
{
[book sortUsingSelector:@selector(compareNames:)] }
其中:
@selector(compareNames:)
//創(chuàng)建一個 SEL 類型的 selector,sortUsingSelector:使用該方法比較數(shù)組中的兩個元素, sortUsingSelector:方法需要完成這樣的比較,它先調(diào)用這個指定的selector 方法,然后向數(shù)組(接受 者)的第一條記錄發(fā)送消息,比較其參數(shù)和此記錄。指定方法的返回值為NSComparisonResult 類型,返 回值為:若小于返回NSOrderedAscending;相等返回 NSOrderedSame;大于返回NSOrderedDescending -(NSComparisonResult)compareNames:(id)element
{
return [name compare:[element name]];
}
NSDictionary: (關(guān)鍵字和定義的組合)
NSDictionary 通常在給定一個關(guān)鍵字(通常是一個NSString 字符串)下存儲一個數(shù)值(可以是任何類
型的對象) 。然后你可以使用這個關(guān)鍵字查找相應的數(shù)值。
使用 dictionaryWithObjectsAndKeys :來創(chuàng)建字典
+ (id)dictionaryWithObjectsAndKeys :(id)firstObject , . . .
例如:
Tire *t1 = [Tire new];
NSDictionary *tires = [ NSDictionary dictionaryWithObjectsAndKeys :t1,@"front-left",nil];
使用方法 objectForKey :來獲取字典中的值
- (id)objectForKey :(id)akey;
查找輪胎可以這樣:
Tire *tire = [tires objectForkey : @"front-left"];
創(chuàng)建新的 NSMutableDictionary 對象,向類 NSMutableDictionary 發(fā)送 dictionary 消息。也可以使用 dictionaryWithCapacity: 方法來創(chuàng)建新的可變字典
+ (id)dictionaryWithCapacity:(unsigned int)numItems ; 可以使用方法setObject :forKey :方法給字典添加元素 setObject : forKey :(id)aKey
下面是另一種使用發(fā)送 dictionary 消息來創(chuàng)建字典的方法:
NSMutableDictionary *tires;
tires = [NSMutableDictionary dictionary] ;
[tires setObject :t1 forKey :@"front-left"];
...
注:若對字典中已有的關(guān)鍵字使用setObject :forKey :方法,則用新的替換
可以使用 removeObjectForKey : 方法來刪除可變字典中的一個關(guān)鍵字 - (void)removeObjectForKey:(id)aKey ;
注:不要去創(chuàng)建 NSString、NSArray 或 NSDictionary 的子類,實在要的話可以用復合的方式來解決問題。
使用這種方法枚舉詞典:
for(NSString *key in g) {
... }
集合對象:
Set 是一組單值對象的集合,有可變和不可變,操作包括:搜索、添加、刪除集合中的成員(僅用于可變 集合) 、比較兩個集合,計算兩個集合的交集和并集等。
#import <Foundation/NSSet.h>
常用的 NSSet 方法
方法
說明
+(id)setWithObjects:obj1,obj2,...,nil
使用一列對象創(chuàng)建新集合
-(id)initWithObjects:obj1,obj2,...,nil
使用一列對象初始化新分配的集合
-(NSUInteger)count
返回集合的成員個數(shù)
-(BOOL)containsObject:obj
確定集合是否包含 obj
-(BOOL)member:obj
使用 isEqual: 方法確定集合是否包含obj
-(NSEnumerator *)objectEnumerator
為集合中的所有對象返回一個 NSEnumerator 對象
-(BOOL)isSubsetOfSet:nsset
確定 receiver 的每個成員是否都出現(xiàn)在 nsset 中
-(BOOL)intersectsSet:nsset
確定是否 receiver 中至少一個成員出現(xiàn) 在對象 nsset 中
-(BOOL)isEqualToSet:nsset
確定兩個集合是否相等
常用的 NSMutableSet 方法(NSSet 的子類)
方法
說明
-(id)setWithCapacity:size
創(chuàng)建新集合,使其具有存儲 size 個成員的初始空間
-(id)initWithCapacity:size
將新分配的集合設(shè)置為 size 個成員的存儲空間
-(void)addObject:obj
將對象 obj 添加到集合中
-(void)removeObject:obj
從集合中刪除對象 obj
-(void)removeAllObjects
刪除接受者的所有成員
-(void)unionSet:nsset
將對象 nsset 的所有成員昂添加到接受者
-(void)minusSet:nsset
從接受者中刪除 nsset 的左右成員
-(void)intersectSet:nsset
將接受者中的所有不屬于 nsset 的元素刪除
注:NSInteger 不是一個對象,基本數(shù)據(jù)類型的 typedef,被 typedef 成 64 位的 long 或 32 位 int
各種數(shù)值: NSNumber:
可以使用對象來封裝基本數(shù)值。
NSNumber 類來包裝基本數(shù)據(jù)類型。
+ (NSNumber *)numberWithChar :(char)value ;
+ (NSNumber *)numberWithInt :(int )value ;
+ (NSNumber *)numberWithFloat :(float)value ;
+ (NSNumber *)numberWithBool :(BOOL)value ;
還有包括無符號版本和各種 long 型數(shù)據(jù)及 long long 整型數(shù)據(jù)
例如:NSNumber *number = [NSNumber numberWithInt : 42] ;
將一個基本類型封裝到NSNumber 后,可以使用下列方法重新獲得:
-
- ?(char)charValue;
-
- ?(int)intValue;
-
- ?(float)floatValue;
-
- ?(BOOL)boolValue;
-
- ?(NSString *)stringV alue;
NSV alue:
NSNumber 實際上是 NSV alue的子類, NSV alue可以封裝任意值。 可以用NSV alue將結(jié)構(gòu)放入 NSArray和 NSDictionary 中。
創(chuàng)建新的 NSV alue:
+(NSValue*)valueWithBytes: (const void *) valueobjCType: (const char *)type;
@encode 編譯器指令可以接受數(shù)據(jù)類型的名稱并為你生成合適的字符串。
NSRect rect = NSMakeRect(1,2,30,40);
NSValue* value ;
value = [NSValuevalueWithBytes: &rect objCType: @encode(NSRect)];
使用getValue:來提取數(shù)值 (傳遞的是要存儲這個數(shù)值的變量的地址)(先找地址再取值)
value = [array objectAtIndex : 0];
[ value getV alue: & rect ] ;
注:Cocoa 提供了將常用的struct 型數(shù)據(jù)轉(zhuǎn)化成NSValue的便捷方法:
+ (NSValue*)valueWithPoint :(NSPoint)point ;
+ (NSValue*)valueWithSize :(NSSize)size;
+ (NSValue*)valueWithRect :(NSRect)rect ;
- (NSSize)sizeValue;
- (NSRect)rectValue;
- (NSPoint)pointValue;
NSNull:
在關(guān)鍵字下如果屬性是NSNull表明沒有這個屬性, 沒有數(shù)值的話表明不知道是否有這個屬性[N。SNull null] //總返回一樣的值
+ (NSNull *)null;
例如:
[contast setObject : [NSNull null] forKey: @"home"];
訪問它:
id home = [contast objectForKey : @"home" ] ;
if (home==[NSNullnull]){
...
}
NSFileManager 允許對文件系統(tǒng)進行操作(創(chuàng)建目錄、刪除文件、移動文件或獲取文件信息)
//創(chuàng)建一個屬于自己的 NSFileManager 對象
NSFileManager *manager = [NSFileManager defaultManager] ;
//將代字符‘~’替換成主目錄
NSString *home = [@"~" stringByExpandingTildeInPath];
//輸出文件的擴展名
- (NSString*)pathExtension
示例:翻查主目錄,查找.jpg 文件并輸出找到的文件列表 //*********************************************************************************
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileManager *manager;
manager = [NSFileManager defaultManager];
NSString *home;
home = [@"~" stringByExpandingTildeInPath];
NSDirectoryEnumerator *direnum;
direnum = [manager enumeratorAtPath: home];
NSMutableArray *files;
files = [NSMutableArray arrayWithCapacity:42];
NSString *filename;
while (filename = [direnum nextObject]) {
if ([[filename pathExtension] isEqualTo:@"jpg"]) { [files addObject: filename];
} }
NSEnumerator *fileenum;
fileenum = [files objectEnumerator];
while (filename = [fileenum nextObject]) {
NSLog (@"%@", filename);
}
[pool drain];
return 0; }
//*********************************************************************************