Foundation 框架的三大資料型別——字串、陣列與字典——幾乎支撐了日常開發的所有資料處理。以下按型別整理最常使用的方法,並在每段程式碼前標明意圖。
// 1. 常數字串
NSString *astring = @"This is a String!";
// 2. 先配置再賦值(注意:賦值後舊物件位址改變,MRC 下需留意記憶體)
NSString *astring = [[NSString alloc] init];
astring = @"This is a String!";
// 3. initWithString: 速度較快
NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];
// 4. 由 C 字串建立
char *Cstring = "This is a String!";
NSString *astring = [[NSString alloc] initWithCString:Cstring];
// 5. 格式化字串,% 加一個字元構成佔位符
int i = 1, j = 2;
NSString *astring = [[NSString alloc] initWithString:
[NSString stringWithFormat:@"%d.This is %i string!", i, j]];
// 6. 臨時字串(自動釋放,不需自行 release)
NSString *astring = [NSString stringWithCString:"This is a temporary string"];
// 從檔案讀入 NSString *path = @"astring.text"; NSString *astring = [[NSString alloc] initWithContentsOfFile:path]; // 寫入檔案 NSString *astring = [[NSString alloc] initWithString:@"This is a String!"]; [astring writeToFile:path atomically:YES];
最基礎的是 isEqualToString:,回傳 BOOL:
BOOL result = [@"This is a String!" isEqualToString:@"This is a String!"];
compare: 回傳的是 NSComparisonResult,共三種值:NSOrderedSame 表示兩者相同;NSOrderedAscending 表示接收者排在前面(astring02 大於 astring01 時為真);NSOrderedDescending 則相反。
若要忽略大小寫,有兩種寫法:
// 寫法一
BOOL result = [astring01 caseInsensitiveCompare:astring02] == NSOrderedSame;
// 寫法二,可同時搭配其他選項
BOOL result = ([astring01 compare:astring02
options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame);
常用 options 包含:NSCaseInsensitiveSearch 不區分大小寫、NSLiteralSearch 完全比對、NSNumericSearch 以數值而非字元順序比較(因此 "v2" 會排在 "v10" 前面)。
NSString *string1 = @"A String"; NSString *string2 = @"String"; [string1 uppercaseString]; // 全部大寫 [string2 lowercaseString]; // 全部小寫 [string2 capitalizedString]; // 各單字首字母大寫
NSString *string1 = @"This is a string"; NSString *string2 = @"string"; // 搜尋子串,回傳 NSRange NSRange range = [string1 rangeOfString:string2]; NSLog(@"Location:%lu, Length:%lu", (unsigned long)range.location, (unsigned long)range.length); // 從頭截到指定位置(不含該位置字元) [string1 substringToIndex:3]; // 從指定位置(含)一路取到結尾 [string1 substringFromIndex:3]; // 依範圍任意截取 [string1 substringWithRange:NSMakeRange(0, 4)];
NSString *Path = @"~/NSData.txt"; // 展開 ~ 為實際家目錄 NSString *absolutePath = [Path stringByExpandingTildeInPath]; // 反向操作,把家目錄縮寫回 ~ [absolutePath stringByAbbreviatingWithTildeInPath]; // 取副檔名 [Path pathExtension];
// 預先配置容量 NSMutableString *str = [NSMutableString stringWithCapacity:40]; NSMutableString *s1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"]; // 附加內容 [s1 appendString:@", I will be adding some character"]; [s1 appendFormat:@"%@", @"格式化附加"]; // 刪除指定範圍 [s1 deleteCharactersInRange:NSMakeRange(0, 5)]; // 在指定位置插入 [s1 insertString:@"Hi! " atIndex:0]; // 整體替換內容 [s1 setString:@"Hello Word!"]; // 替換指定範圍 [s1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@"That"];
NSString *String1 = @"NSStringInformation.txt"; [String1 hasPrefix:@"NSString"]; // 是否以該字串開頭 [String1 hasSuffix:@".txt"]; // 是否以該字串結尾
NSArray *array = [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", @"Four", nil]; [array count]; // 元素個數 [array objectAtIndex:2]; // 取出指定索引的元素 // 由陣列產生可變陣列 NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
NSArray *oldArray = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
// 1. 逐一 copy 元素(元素層級的複製)
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [oldArray count]; i++) {
[newArray addObject:[[oldArray objectAtIndex:i] copy]];
}
// 2. 快速枚舉
for (id obj in oldArray) {
[newArray addObject:obj];
}
// 3. 深複製
newArray = (NSMutableArray *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault,
(CFPropertyListRef)oldArray,
kCFPropertyListMutableContainers);
// 4. 複製並排序
NSEnumerator *enumerator = [oldArray objectEnumerator];
id obj;
while ((obj = [enumerator nextObject])) {
[newArray addObject:obj];
}
[newArray sortUsingSelector:@selector(compare:)];
差別值得留意:逐一 copy 複製的是元素本身;快速枚舉只是把同一批引用放進新容器;CFPropertyListCreateDeepCopy 才是真正的遞迴深複製。
// 字串切成陣列 NSString *string = @"One,Two,Three,Four"; NSArray *array = [string componentsSeparatedByString:@","]; // 陣列合併成字串 NSString *joined = [array componentsJoinedByString:@","];
NSArray *array = [NSMutableArray arrayWithCapacity:20];
[array addObject:@"Four"]; // 尾端加入
[array removeObjectAtIndex:1]; // 刪除指定索引
// 正向枚舉
NSEnumerator *enumerator = [array objectEnumerator];
id thingie;
while ((thingie = [enumerator nextObject])) {
NSLog(@"thingie:%@", thingie);
}
// 反向枚舉
enumerator = [array reverseObjectEnumerator];
id object;
while ((object = [enumerator nextObject])) {
NSLog(@"object:%@", object);
}
// 快速枚舉
for (NSString *s in array) {
NSLog(@"string:%@", s);
}
// 建立不可變字典(objectsAndKeys 成對出現,以 nil 收尾)
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
@"One", @"1", @"Two", @"2", @"Three", @"3", nil];
NSString *string = [dictionary objectForKey:@"One"];
// 可變字典
NSMutableDictionary *md = [NSMutableDictionary dictionary];
[md setObject:@"One" forKey:@"1"];
[md setObject:@"Two" forKey:@"2"];
[md removeObjectForKey:@"1"];
NSArray 只能放物件,若想把 CGRect 這類結構放進去,得先用 NSValue 包裝:
NSMutableArray *array = [[NSMutableArray alloc] init]; CGRect rect = CGRectMake(0, 0, 320, 480); NSValue *value = [NSValue valueWithBytes:&rect objCType:@encode(CGRect)]; [array addObject:value]; // 取出 value = [array objectAtIndex:0]; [value getValue:&rect];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *home = @"../Users/";
NSDirectoryEnumerator *direnum = [fileManager enumeratorAtPath:home];
NSMutableArray *files = [[NSMutableArray alloc] init];
NSString *filename;
while ((filename = [direnum nextObject])) {
if ([[filename pathExtension] hasSuffix:@"jpg"]) {
[files addObject:filename];
}
}
// 也可以搭配快速枚舉
for (NSString *f in files) {
NSLog(@"object:%@", f);
}
這段程式示範了目錄枚舉器(NSDirectoryEnumerator)搭配路徑副檔名判斷的標準寫法,是檔案批次處理時很常用到的組合。
以上範例多為 MRC 時代寫法。在 ARC 之下,alloc/release 的配對由編譯器代管,不需要也不應該手動呼叫 release;而 Modern Objective-C 提供了更簡潔的字面語法,例如 @[@"a", @"b"] 表示陣列、@{@"key": @"value"} 表示字典、array[0] 取代 objectAtIndex:,實際開發時優先採用這些寫法會讓程式碼清爽不少。