//代碼片斷:(不使用故事板時 用應用類手動建立初始界面) -(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; }
NSString *bundlePathName = [[NSBundle mainBundle] resourcePath]; NSString *filePathName = [NSString stringWithFormat:@"%@/textfile.text",bundlePathName]; NSError *fileError; NSString *textFileContents = [NSString stringWithContentsOfFile:filePathName encoding:NSASCIIStringEncoding error:&fileError]; if(fileError.code == 0) NSLog(@" textFile.text contents : %@",textFileContents); else NSLog(@"error(%ld):%@ ",fileError.code,fileError.description);
ios能夠從包資源目錄中讀取文本文件,但不能向包資源目錄中寫入任何文件,只能寫到文檔目錄中。ios
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject]; NSString *filePathName = [NSString sreingWithFormat:"%@/textfile.txt",documentDirectory]; NSError *fileError; NSString *textFileContents = @"Content generated from ios app."; [textFileContents writeToFile:filePathName atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&fileError]; if(fileError.code == 0) NSLog(@"textfile.text was writtrn successfully with these contents:%@",textFileContents); else NSLog(@"error(%d): %@",fileError.code,fileError.desprition);
比較使用NSRange定義起點與長度的字串web
NSString *alphabet = @"ABCDEFGHIJKLMON"; NSrange range = NSMakeRange(2,3); BOOL lettersInRange = [[alphabet substringWithRange:range] isEqualToString:@"CDE"];
使用NSMutableStringobjective-c
向可變字符串任意位置插入字符json
[myString insertString:@"abcdefg, " atIndex:0]
刪除NSRange範圍指定的字符數組
NSRange range = NSMakeRange(9,3); myString deleteCharactersInRange:range];
將NSRange指定範圍內某個字符替換爲不一樣的字符xcode
NSRange rangeOfString = [myString rangeOfString:myString]; myString replaceOccurrencesOfString:@"," withString:@"|" options:NSCaseInsensitiveSearch range:rangeOfString];
替換NSrange指定範圍的字符緩存
NSRange rangeToReplace = NSMakeRange(0,4); myString replaceCharactersInRange:rangeToReplace withString:@"MORE"];
相似浮點數這樣的原生類型app
folat fNumber = 12; NSString *floatToString = [NSString stringWithFormat:@"%f",fNumber];
若是是NSNumber對象編碼
NSNumber *number = [NSNumber numberWithFloat:30]; NSString *numberToString = [number stringValue];
轉換爲原生類型atom
NSString *aFloatValue = @"12.50"; float f = [aFloatValues floatValue];
轉換爲NSNumber對象
NSNumber *aFloatNumber = [NSNumber numberWithFloat:[aFloatValue floatValue]];
以貨幣的形式將其顯示出來
NSNumber *numberToFormat = [NSNumber numberWithFloat:9.99]; NSNumberFormatter *numberFormatter = [[NSNumberFormat alloc] init]; numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle; NSLog(@"Formatted for currency :%@",[numberFormatter stringFromNumber:numberToFormat]);
使用指定對象初始化數組: NSArray *listOfLetters = [NSArray arrayWithObjects:@"A",@"B",@"C",nil]; 其餘初始化方法: -(id)initWithContentsOfFile:(NSString *)path; -(id)initWithContentsOfURL:(NSURL *)url;
objectAtIndex: 獲取數組中位於摸個整數位置的對象引用 lastObject 獲取數組中最後一個對象的引用 indexOfObject: 獲取對象在數組中的位置
makeObjectsPerformSelector:withObject 能夠傳遞但願每一個對象都執行的方法名和一個參數
[listofObjects makeObjectsPerformSelector:@selector(appendString:) withObject:@"-MORE"]; 向數組中每一個可變字符串發送 appendString:消息
使用enumerateObjectsUsingBlock: (Effective objective c中提過)
[listOfobjects enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop){ NSLog(@" object(%lu) 's description is %@",idx,[obj description]); }];
使用NSSortDescription
使用NSSortDescriptor對象爲每一個Persion屬性提供排序描述符,而後放入數組中
NSSortDescription *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; NSSortDescription *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]; NSSortDescription *sd3 = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES]; NSArray *sdArray1 = [NSArray arrayWithObject:sd1,sd2,sd3,nil];
得到排序好的數組
NSArray *sortArray1 = [persionList sortedArrayUsingDescriptors:sdArray1];
使用NSPredicate對象。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 30"]; NSArray *arraySubset = [listOfObjects filteredArrayUsingPredicate:predicate];
for-each遍歷
for (NSString *s in [dictionary allValues]){ NSLog(@"value: %@ ",s); } for (NSString *s in [dictionary allkeys]){ NSLog(@"key: %@",s) }
使用enumerateKeysAndObjectsUsingBlock:
[dictionary enumeraKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop){ NSLog(@"key = %@ and obj = %@",key,obj); }];
使用NSSet 與 NSMutableSet
NSSet *set = [NSSet setWithObjects:@"Hello World",@"Bonjour tout le monde",@"Hola Mundo",nil]; 其餘建立方式 -(id)initWithArray:(NSArray *)array;
NSSet *set1 = [NSSet setWithObjects@"A",@"B",@"C",@"D",@"E",nil]; NSSet *set2 = [NSSet setWithObjects@"D",@"E",@"F",@"G",@"H",nil]; //判斷兩個集合是否相交 BOOL setsIntersect = [set1 intersectsSet:set2]; //判斷某個集合包含餓的對象是否所有位於兩一個集合中 BOOL set2IsSubset = [set2 isSubsetofSet:set1]; //判斷兩個集合是否相等 BOOL set1ISEqualToSet2 = [set1 isEqualToSet:set2]; //判斷某個對象是否位於集合中 BOOL set1ContainsD = [set1 containsObject:@"D"];
使用 for-each
for(NSString *s in [set allObjects]){ NSLog(@" value:%@ ",s); }
使用enumerateObjectsUsingBlock:
[set enumerateObjectsUsingBlock:^(id obj,BOOL *stop){ NSLog(@" obj = @% ",obj); }];
得到指向應用包得引用
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
得到其餘目錄:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirctory,NSUserDomainMask,YES)lastObject]; //用戶生成內容的位置 NSDocumentDirectory //應用的庫目錄 NSLibraryDirectory //緩存文件的目錄 NSCachesDirectory
獲取文件屬性
NSFileManager *fileManager = [NSDileManager defaultManager]; NSString *filePathName = @"/User/shared/textfile.txt"; NSError *error = nil; NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePathName error:&error]; if(!error){ NSDate *dateFileCreated = [fileAttributes valueForKey:NSFileCreationDate]; NSString *fileType = [fileAttributes valueForKey:NSFileType]; }
目錄常量 | 說明 |
---|---|
NSFileType | 文件類型 |
NSFileSize | 文件大小(字節) |
NSFileModificationDate | 文件上次修改的時間 |
NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *sharedDirectory = @"/Users/Shared"; NSerror *error = nil; NSArray *listOfFiles = [fileManager contentsofDirectoryAtPath:sharedDirectory error:&error]; NSArray *listSubPath = [fileManagersubpathsOfDirectoryAtPath:sharedDirectory error:&error];
操做 | 方法 |
---|---|
新建目錄 | createDirectoryAtPath:withIntermediateDirectories:attributes:error: |
移動目錄 | moveItemAtPath:toPath:error |
刪除目錄 | removeItemAtPath:error: |
複製目錄 | copyItemAtPath:toPath:error |
BOOL directoryCreated = [fileManager createDirectoryAtPath:newDirectory withIntermediateDirectories:YES attributes:nil error:&error]; BOOL directoryMoved = [fileManager moveItemAtPath:newDirectory toPath:directoryMovedTo error:&error]; BOOL directoryCopied = [fileManager copyItemAtPath:directoryToCopy toPath:directoryToCopyTo error:&error];
操做 | 方法 |
---|---|
新建文件 | createFileAtPath:contents:attributes: |
移動文件 | moveItemAtPath:error |
刪除文件 | removeItemAtPath:error: |
複製文件 | copyItemAtPath:toPath:error: |
NSFileManager *fileManager = [NSFileManager defaultManager]; NSURL *url = [NSURL URLWithString:@"http://xxx.xx.jpg"]; NSData *dataObject = [NSData dataWithContentOfURL:url]; NSString *newFile = @"/Users/shared/xx.jpg"; BOOL fileCreated = [fileManager createFileAtPath:newFile contents:dataObject attributes:nil];
狀態 | 方法 |
---|---|
文件是否存在 | fileExistsAtPath: |
文件是否可讀 | isReadableFileAtPath: |
文件是否可寫 | isWritableFileAtPath:filePathName |
文件是否可執行 | isExcutableFileAtPath: |
文件是否可刪除 | isDeletableFileAtPath: |
NSDate *todaysDate = [NSData date];
//使用NSDateComponents NSDateComponents *dateComponents = [[NSDateComponent alloc]init]; //設置日期屬性 dateComponents.year = 2007; dateComponents.month = 6; dateComponents.day = 29; dateComponents.hour = 12; dateComponents.minute = 01; dateComponents.second = 31; //加利福尼亞州 dateComponents.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"PDT"]; //建立NSDate對象 NSDate *iPhoneReleaseDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
操做 | 方法 |
---|---|
判斷是否相等 | isEqualToDate: |
判斷某個日期是否遭遇另外一個日期 | earlierDate: |
判斷哪一個日期更晚 | laterDate: |
得到兩個日期之間相差的秒數 | 使用 timeIntervalSinceDate: 並將第二個日期做爲參數 ,或者使用NSDateComponents 、 NSCalendar |
//得到系統日曆引用 NSCalendar *systemCalendar = [NSCalendar currentCalendar]; //經過對NSCalendar常量進行安慰或運算來制定採用的時間單位 Unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; //返回NSDateComponents對象 NSDateComponents *dateComparisonComponents = [systemCalendar components:unitFlags fromDate:iPhoneReleaseDate toDate:todaysDate options:NSWrapCalendarComponents];
NSString *dateString = @"02/14/2012"; NSDateFormatter *df = [[NSDateFormatter alloc]init]; df.dateFormate = @"MM/dd/yyyy"; NSDate *valentinesDay = [df dateFromString:dateString];
df.dateFormate = @"EEEE, MMMM d" ; [sd stringFromDate:valentiesDay]; //結果是 Tuesday, February 14
//得到情人節前一週的時間 NSDateComponents *weekBeforeDateComponents = [[NSDateComponents alloc]init]; weekBeforeDateComponents.week = -1; NSDate *vDayShoppingDay = [[NScalendar currentCalendar] dateByAddingComponents:weekBeforeDateComponents toDate:valentiesDay options:0];
//使用 NSData和NSURL NSURL *remoteTextFileURL = [NSURL URLWithString:@"http://xxx.xxx.xxx/xxx.text"]; NSData *remoteTextFileData = [NSData dataWithContentsOfURL:remoteTextFileURL]; [remoteTextFileData writeToFile:@"/User/shared/xxx.txt" atomically:YES];
//使用NSXMLParserDelegate //在讀到每一個新的XML元素時執行一次 parser:didStartElement:namespaceURI:qualifiedName:attributes //在每次遇到文件中的XML元素的數據時執行 -(void)parse:(NSXMLParse*)parse foundCharacters:(NSString*)string
//JSON : {"Person":"Mattew J. Campbell","Gender":"Male"} NSError *error; NSDictionary *bitlyJson = [NSJSonSericalization JSONObjectWithData:responseData options:0 error:&error]; if(!error){ NSString *Person = [bitlyJson objectForKey:@"Person"]; }
//獲取對象中的name屬性 id temp; temp = [workProject01 valueForKey:@"name"] ; //經過kvc設置屬性值 [workProject01 setValue:@"my Pet Project" forKey:@"name"];
//一般經過點符號查看屬性 id temp; temp = workProject01.persionInCharge.name; //使用鍵路徑 temp = [workProject01 valuesForKeyPath:@"personInCharge.name"]; //使用鍵路徑設置屬性 [workProject01 setValue:@"Mary steinbeck" forKeyPath:@"personInCharge.name"];
使用@count、@sum、@avg、@min、@max與@distinctUnionOfObject得到對象圖數組中的聚合信息
//listOfTasks 是Task對象的數組。每一個Task對象都有名爲priority的int類型屬性 //得到priority值的總數 id sum = [workProject01 valuesForKeyPath:@"listOfTasks.@sum.priority"]; //get the averageof all the priority values id average = [workProject01 valuesForKeyPath:@"listOfTasks.@avg.priority"]; //Get the minumum of all the priority values id min = [workProject01 valuesForKeyPath:@"listOfTasks.@min.priority"]; //Get the maximum of the priority values id max = [workProject01 valuesForKeyPath:@"listOfTasks.@max.priority"]; //獲取不重複的對象列表 id listOfWorkers = [workProject-1 valueForKeyPath:@"listOfTasks.@distinctUnionOfObjects.assignedWorker"];
使用NSObject內置方法來探查類來知曉某個對象是不是某個類的實例,對象是否會響應選擇器,以及對象是否等於另外一個對象。
//使用respondsToSelector查看是否能響應消息 //查看projectManager是否有writeReportToLog方法 id projectManager = [workProject01 valueForKey:@"personInCharge"]; BOOL doesItRespond = [projectManager respondsToSelector@selector(writeReportToLog)] ; //使用isKindOfClass判斷某個對象是不是某個類或子類的實例 BOOL isItAKindOgClass = [consulter isKindOfClass:[Worker class]]; isItKindOfClass = [projectManager isKindOfClass:[Worker class]]; //使用isMemberOfClass盤算某個對象是不是某個類的實例(不包括子類) BOOL isAnInstanceOfClass = [projectManager isMemberOfClass:[Worker class]]; isAnInstanceOfClass = [consulter isMemberOfClass:[Worker class]]; //判斷兩個對象引用是否指向相同的對象 BOOL is Equal = [projectManager isEqual:consulter];
使用NSCoding協議中的 encodeWithCoder: 與 initWithCoder
//向Worker.m中的Worker(name,role)實現添加encodeWithCoder 和 initWithCoder -(void) encodeWithCoder:(NSCoder*)encoder{ [encoder encodeObject:self.name forKey:@"namekey"]; [encoder encodeObject:self.role forKey:@"rolekey"]; } -(id)initWithCoder:(NSCoder*)decoder{ self.name = [decoder decodeObjecyForKey:@"namekey"]; self.role = [decoder decodeObjectForKey:@"rolekey"]; return self; }
而後使用NSKeyedArchiver保存或者取出對象
//保存 BOOL dataArchived = [NSKeyArchiver archiveRootObject:workProject01 toFile:@"/Users/Shared/workProject01.dat"] ; if(dataArchived) NSLog(@" object graph successfully archived "); else NSLog(@" Error attempting to archive object garph "); //恢復 Project *storedProject = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Shared/workProject01.dat"]; if(storedProject) [storedProject writeReportToLog]; else NSLog(@"Error attempting to retrieve the object graph");