《Objective-c开发范例代码大全》
第一章 应用开发
1.12 从Xcode创建IOS应用
//代码片段:(不使用故事板时 用应用类手动创建初始界面)
-(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;
}
第二章 使用字符串与数字
2.3 在ios上从文件读取字符串
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);
2.5 在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);
2.6 比较字符串
- 使用isEqualToString:
- 查看字符串是否具有匹配的前缀 hasPrefix
- 查看字符串是否具有匹配的后缀 hasSuffix
比较使用NSRange定义起点与长度的字串
NSString *alphabet = @"ABCDEFGHIJKLMON"; NSrange range = NSMakeRange(2,3); BOOL lettersInRange = [[alphabet substringWithRange:range] isEqualToString:@"CDE"];
2.7操纵字符串
使用NSMutableString
- 向可变字符串末尾追加字符串 appendString
向可变字符串任意位置插入字符
[myString insertString:@"abcdefg, " atIndex:0]
删除NSRange范围指定的字符
NSRange range = NSMakeRange(9,3); myString deleteCharactersInRange:range];
将NSRange指定范围内某个字符替换为不同的字符
NSRange rangeOfString = [myString rangeOfString:myString]; myString replaceOccurrencesOfString:@"," withString:@"|" options:NSCaseInsensitiveSearch range:rangeOfString];
替换NSrange指定范围的字符
NSRange rangeToReplace = NSMakeRange(0,4); myString replaceCharactersInRange:rangeToReplace withString:@"MORE"];
2.8 搜索字符串
- 使用 rangeOfString:options:range: 然后判断返回的NSRange.location是否为NSNotFound即可
2.10 将数字转换为字符串
类似浮点数这样的原生类型
folat fNumber = 12; NSString *floatToString = [NSString stringWithFormat:@"%f",fNumber];
如果是NSNumber对象
NSNumber *number = [NSNumber numberWithFloat:30]; NSString *numberToString = [number stringValue];
2.11 将字符串转换为数字
转换为原生类型
NSString *aFloatVa