您的位置:首页 > 移动开发 > Objective-C

《Objective-c开发范例代码大全》

2015-11-23 18:19 627 查看

《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 *aFloatValue = @"12.50";
float f = [aFloatValues floatValue];


转换为NSNumber对象

NSNumber *aFloatNumber = [NSNumber numberWithFloat:[aFloatValue floatValue]];


2.12 格式化数字

以货币的形式将其显示出来

NSNumber *numberToFormat = [NSNumber numberWithFloat:9.99];
NSNumberFormatter *numberFormatter = [[NSNumberFormat alloc] init];
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSLog(@"Formatted for currency :%@",[numberFormatter stringFromNumber:numberToFormat]);


第三章 使用对象集合

3.1创建数组

使用指定对象初始化数组:
NSArray *listOfLetters = [NSArray arrayWithObjects:@"A",@"B",@"C",nil];

其他初始化方法:
-(id)initWithContentsOfFile:(NSString *)path;
-(id)initWithContentsOfURL:(NSURL *)url;


3.2 引用数组中对象

objectAtIndex: 获取数组中位于摸个整数位置的对象引用
lastObject 获取数组中最后一个对象的引用
indexOfObject: 获取对象在数组中的位置


3.4遍历数组

for-each 遍历

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]);
}];


3.5排序数组

使用NSSortDescription

自定义类Person优三个属性 firstName、lastName、age

使用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];

3.6查询数组

使用NSPredicate对象。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 30"];
NSArray *arraySubset = [listOfObjects filteredArrayUsingPredicate:predicate];


3.7操纵数组内容

使用NSMutableArray

插入对象 insertObject:atIndex:

替换对象 replaceObjectAtIndex:withObject

交换数组中的对象 exchangeObjectAtIndex:withObjectAtIndex:

删除对象

removeObject

removeObjectAtIndex:

removeLastObject

removeAllObjects

3.13 遍历字典

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);

}];

3.17 创建集合

使用NSSet 与 NSMutableSet

NSSet *set = [NSSet setWithObjects:@"Hello World",@"Bonjour tout le monde",@"Hola Mundo",nil];
其他创建方式
-(id)initWithArray:(NSArray *)array;


3.19 比较集合

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"];


3.20 遍历集合

使用 for-each

for(NSString *s in [set allObjects]){
NSLog(@" value:%@ ",s);
}


使用enumerateObjectsUsingBlock:

[set enumerateObjectsUsingBlock:^(id obj,BOOL *stop){
NSLog(@" obj = @% ",obj);
}];


第四章 文件系统

4.3 获得指向关键iOS目录的引用

获得指向应用包得引用

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文件上次修改的时间

4.5获得目录下的文件与子目录列表

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *sharedDirectory = @"/Users/Shared";
NSerror *error = nil;
NSArray *listOfFiles = [fileManager contentsofDirectoryAtPath:sharedDirectory error:&error];
NSArray *listSubPath = [fileManagersubpathsOfDirectoryAtPath:sharedDirectory error:&error];


4.6管理目录

操作方法
新建目录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];


4.7新建文件

操作方法
新建文件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];

4.8 查看文件状态

状态方法
文件是否存在fileExistsAtPath:
文件是否可读isReadableFileAtPath:
文件是否可写isWritableFileAtPath:filePathName
文件是否可执行isExcutableFileAtPath:
文件是否可删除isDeletableFileAtPath:

第5章 日期、时间与定时器

5.1创建表示今天的日期对象

NSDate *todaysDate = [NSData date];


5.2通过Component创建自定义日期

//使用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];


5.3 比较两个日期

操作方法
判断是否相等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];

5.4 将字符串转换为日期

NSString *dateString = @"02/14/2012";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.dateFormate = @"MM/dd/yyyy";
NSDate *valentinesDay = [df dateFromString:dateString];


5.5 格式化日期以便显示

df.dateFormate = @"EEEE, MMMM d"          ;
[sd stringFromDate:valentiesDay];
//结果是 Tuesday, February 14


5.6 加减时间

//获得情人节前一周的时间
NSDateComponents *weekBeforeDateComponents = [[NSDateComponents alloc]init];
weekBeforeDateComponents.week = -1;
NSDate *vDayShoppingDay = [[NScalendar currentCalendar] dateByAddingComponents:weekBeforeDateComponents toDate:valentiesDay options:0];


第7章 使用Web服务

7.1下载数据

//使用 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];


7.2 解析XML文件

//使用NSXMLParserDelegate

//在读到每个新的XML元素时执行一次
parser:didStartElement:namespaceURI:qualifiedName:attributes
//在每次遇到文件中的XML元素的数据时执行
-(void)parse:(NSXMLParse*)parse foundCharacters:(NSString*)string


7.3解析JSON

//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"];
}


第9章 使用对象图

9.2 使用键-值编码

//获取对象中的name属性
id temp;
temp = [workProject01 valueForKey:@"name"]  ;

//通过kvc设置属性值
[workProject01 setValue:@"my Pet Project" forKey:@"name"];


9.3 在对象图中使用键路径

//通常通过点符号查看属性
id temp;
temp = workProject01.persionInCharge.name;
//使用键路径
temp = [workProject01 valuesForKeyPath:@"personInCharge.name"];
//使用键路径设置属性
[workProject01 setValue:@"Mary steinbeck" forKeyPath:@"personInCharge.name"];


9.4 使用键路径聚合信息

使用@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"];


9.5 实现观察者模式

当某个对象的属性值发生变化时,另一个对象会得到通知。

在被观察的对象和观察对象之间建立连接。

向被观察对象(指含有指向观察对象的引用)发送 addObsever:forKeyPath:options:context:

观察对象的类定义中重写NSObject的observeValueForKeyPath:ofObject:change:context:

该方法会接受到 例如发生变化的对象、键路径以及变化的属性值等信息

最后被观察的对象必须在dealloc方法中删除观察者

9.6 探查类与对象

使用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];


9.7 归档对象图

使用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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: