//代码片断:(不使用故事板时 用应用类手动建立初始界面) -(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");