[不断更新]iOS开发常用技术

1.修改默认初始化方法 构建便利构造器

修改默认init初始化
.m文件中
@implementation 类名
-(id)init{
  self=[super init];
  printf("xxx");
  if(self){
  name=@"xxx";
  age=36;
  xx=xxx;
  }
  return self;
 }
}
@end
main中
@autoreleasepool{
xxx* xx=[[xx alloc]init(默认方式)];
}

根据名字(可使用多条件)初始化
.m文件中
-(id)initName:(NSString)n{
  self=[super init];
  if(self){
  name=@"xxx";
  age=36;
  xx=xxx;
  }
  return self;
 }
}
@end
main中
@autoreleasepool{
   xxx* xx=[[xx alloc]initName];
}

 

2.重写系统description方法 用于测试

#pragma mark 描述 NSLog(@"%@",对象名);
-(NSString*)description{
   return [NSString stringWithFormat:@"uid=%d",[self getUid]];
}

 

3. NSString相关操作

NSString不可变字符串/NSMutableString可变字符串
创建字符串
1.字面量 NSString* str=@"xxx"; 常用
2.new NSString* str=[NSString new]; 不推荐
3.实例化 NSString* str=[[NSString alloc]initWithString:@"xxx"]; 常用
4.便利构造器 NSString* str=[NSString stringWithFormat:@"格式",变量]; 重点
   文件 a01.jpg...a20.jpg
   for(i=1;i<=20;i++)
   NSString* str=[NSString stringWithFormat:@"a%02d",i];
5.通过字符数组初始化
   char c[]=@"xxx";
   NSString* str=[[NSString alloc]initWithCString:c encoding:UTF8String];

NSString常用消息
获取字符串长度
NSInteger length=[str length];

根据索引得到单个字符
unichar c=[str charactorAtIndex:5]; //索引从0开始

从某个位置截取字符串(获得子串)
NSRange range={1,2}; //1为索引位置 2为截取长度
NSString* str=[str subStringWithRange:range];
eg.
NSString* str=@"helloworld";
NSRange r={1,3};
NSString* result=[str subStringWithRange:r];
NSLog(@"%@",result);
-> ell

//取.jpg前的值
NSRange range;
NSString* demo=@"xxx.jpg";
range=[demo rangeOfString:@"."];
   if(range.length==0){
     printf("Nothing Match!\n");
   }
NSRange find={0,range.location};
NSString* result=[demo subStringWithRange:find];
NSLog(@"%@",result);

叠加字符串 appendString(NSMutableString适用)
NSMutableString* str=[[NSMutableString alloc]init];
[str appendString:@"123"];
[str appendString:@"456"];
NSLog(@"%@",str);
->123456

 

4.NSArray相关操作

NSArray数组遍历
1.循环法
for(int i=0 ; i<str.count ; i++)
{
     NSLog(@"%@",str[i]);
}
2.迭代器(OC中专门遍历数组的方法 效率更高)
NSEnumerator* it=[str objectEnumerator];
id object;
while(object=[it nextObject])
{
   NSLog(@"%@",object);
}

使用字面量输入数据
NSArray* array=@[stu1,stu2,@"xxx"];

输出数组元素个数
NSLog(@"count=%ld",array.count);

输出数组所有元素
NSLog(@"%@",array);

取得数组第4个元素
NSLog(@"4th%@",[array objectAtIndex:3]);

NSMutableArray*
为可变数组根据所占空间实例化
NSMutableArray* muArray=[NSMutableArray arrayWithCapacity:6];

为可变数组添加数据
[muArray addObject:@"xxx"];

根据索引为可变数组插入/删除数据
[muArray insert/removeObject:@"xxx" atIndex:4];

遍历可变数组
for(NSObject* object  in muArray){
   NSLog(@"%@",object);
}

 

5.NSDictionary相关操作

创建NSDictionary
NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:@"object1",@"key1",nil]; //字典必须以nil结尾

以文件内容初始化字典
NSDictionary* dic=[NSDictionary dictionaryWithContentsOfFile:path];

通过字面量创建字典
NSDictionary* dic=@{@"k01":@"xxx",@"k02":@(10)}; //数字直接用@( )放入字典

输出字典内容
NSLog(@"%@",dic);

取得字典长度
[dic count];

通过键输出字典内容
NSLog(@"%@",[dic objectForKey:@'k01"]);
NSLog(@"%@",dic[@"k01"]);

遍历字典(只取得value或key)
NSEnumerator* it=[dic object/keyEnumertor];
id object;
while(object=[it nextObject])
{
   NSLog(@"%@",object);
}

取得所有的键
NSArray* array=[dic allKeys];

NSMutableDictionary*
创建并初始化
NSMutableDictionary* dic=[NSMutableDictionary dictionaryWithCapacity:10];

向字典动态添加数据
[dic setObject:@"xxx" forKey:@"xxx"];

 

6.KVC键值编码

KVC Key-Value-Coding
间接访问实例变量的方法
Student* stu=[[Student alloc]init];
[stu setValue:@"xxx" forKey:@"name"];
NSString* name=[stu valueForKey:@"name"];
NSLog(@"学生姓名=%@",name);

 

7.NSDate相关操作

获取当前时间
NSDate* now=[NSDate date];
NSLog(@"%@",now);

取得两个时间对象间隔
NSDate* now=[NSDate date];
NSDate* tomorrow=[[NSDate alloc]initWithTimeIntervalSinceNow:24*60*60];
NSLog(@"%@",[now timeIntervalSinceDate:tomorrow]);

 

8.Protocol协议实现方法

protocol 协议
协议只能放方法的声明

创建协议
New->File->Objective-C->Protocol
Protocol.h文件
@protocol 协议名<NSObject(父协议)>
@required (必须实现)
@optional (可选)
@end

使用协议
.h文件中 #improt"ProtocolName.h" 父类名后加<ProtocolName>
.m文件中 实现协议功能

判断方法是否实现
测试协议时使用
if [对象 respondsToSelector:@Selector(方法名)]{
   [对象 方法名];
   };
OC中方法是SEL(@Selector)类

 

9.Delegate委托代理

delegate 委托代理
类自己不能完成的消息 让别的类去做
实际应用时 区分委托代理是谁 谁需要帮助 谁需要遵守协议

创建委托代理模式
1.创建协议 声明能帮助其它类的消息
2.需要帮助的类
->NeedHelp.h中
#import"ProtocolName.h"
父类名后不要加<ProtocolName>//只导入协议 不遵守协议
->声明delegate属性
@property(nonatomic,assign)id<ProtocolName>delegate
->NeedHelp.m中
->需要帮助的消息中写
if(self.delegate&&[self.delegate respondsToSelector:@selector(帮助该类的消息)])
{
   [self.delegate 帮助该类的消息];
};
else ...
3.委托代理的类
->Helper.h中
#import"ProtocolName.h"父类名后加<ProtocolName>
->Helperm中
实现协议中声明的功能
4.实例化对象
NeedHelp类的对象.delegate=委托代理类的对象;

 

10.NSTimer相关操作

NSTimer
{
   int count;
   NSTimer* TimeStop;
}
-(id)init
{
   self=[super init];
   count=0;
   [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doHomework) userInfo:nil repeats:YES];
   if(count==100)
   [TimeStop invalidate];
   return self;
}
-(void)doHomeWork
{
   count++;
   printf("HomeWork %d\n",count);
}
int main()
{
   Student* stu=[[Student alloc]init];
   [stu doHomeWork];
   [[NSRunLoop currentRunLoop]run];
   //单独的NSTimer类对象使用[timer fire];方法启动计时器
}

 

11.NSNotificationCenter通知中心

NSNotificationCenter 通知中心
实现了观察者模式 允许应用的不同对象以松耦合的方式进行通信

创建通知中心
1.通知中心是系统中的单例
不用单独创建 直接使用即可
2.设定观察者observer
在观察者observer.m中 需要设定观察的消息中写入
-(void)observer
{
   NSNotificationCenter* nc=[NSNotificationCenter defaultCenter];
   //SEL为观察者需要执行的代码 Name为通知中心根据这个名字进行通知观察者
   [nc addObserver: self selector:@selector(SEL) name:@"Name" object:nil];
}
3.设定发送者poster
在发送者poster.m中 需要设定发送的消息中写入
-(void)poster
{
   NSNotificationCenter* nc=[NSNotificationCenter defaultCenter];
   //Name为poster发送到通知中心的标记 object为发送消息的对象
   [nc postNotificationName:@"Name" object:self];
}
4.main中直接实例化观察者和发送者
先创建[观察者对象 observe];进行观察 再创建被观察者执行消息

 

12.单例模式

单例
类中的对象有且只有一个

单例方法命名
多以shared类名 或 default类名开头

.h文件
+(id)sharedClassName;

.m文件
#import "ClassName.h"
@implementation
ClassName
Static ClassName* shared=nil;
+(id)sharedClassName{
   static dispatch_once_t xx;
   dispatch_once(&xx,^{
       if(shared==nil){
       shared=[[super allocWithZone:Null]init];
       }
   });
   return shared;
}
-(id)copyWithZone:(NSZone*)zone
{
   return self;
}
+(instancetype)allocWithZone:(NSZone*)zone
{
   return [self sharedClassName];
}
@end

 

13.FMDB数据库操作

FMDB常用类
FMDatabase : 一个单一的SQLite数据库 用于执行SQL语句
FMResultSet :执行查询一个FMDatabase结果集 这个和android的Cursor类似
FMDatabaseQueue :在多个线程来执行查询和更新时会使用这个类

建立FMDB
1.把FMDB文件夹复制到项目根目录
2.把FMDB文件拖入项目
3.project-> BuildPhases-> LinkBinaryWithLibraries-> +Libsqlite3.dylib

使用FMDB
1.导入头文件
#import"FMDatabase.h"
2.建立数据库
NSString* path=@"xx/xx/xx.db"; //xx/xx/xx为建立数据库路径 可以把路径定义成宏 方便更改
FMDatabase* db=[FMdatabase databaseWithPath:path]; //参数为上面定义的path
* 当数据库文件不存在时 fmdb会自己创建一个
* 如果传入的参数是空串:@"" 则fmdb会在临时文件目录下创建这个数据库 数据库断开连接时 数据库文件被删除
* 如果传入的参数是 NULL 则它会建立一个在内存中的数据库 数据库断开连接时 数据库文件被删除
if(![db open]){
   printf("Error!\n"); //如果没有打开数据库则显示Error
}
else{
   printf("Success!\n");
}
[db close]; //建立后关闭数据库
3.建表
NSString* sql=@"create table if not exists tablename(列名1,列名2);";
4.数据库增删改等操作
除了查询操作 FMDB数据库操作都执行executeUpdate方法 这个方法返回BOOL型
NSString* sql...
5.数据查询操作
查询操作使用了executeQuery 并涉及到FMResultSet
if ([db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@",TABLENAME];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            int Id = [rs intForColumn:ID];
            NSString * name = [rs stringForColumn:NAME];
            NSString * age = [rs stringForColumn:AGE];
            NSString * address = [rs stringForColumn:ADDRESS];
            NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);
        }
        [db close];
}

 

14.通过Tag查找视图

通过tag查找视图
tag是UIView的属性
UIView* view1=[[UIView alloc]initWithFrame:CGRectMake:( 0, 0, 100, 100)];
view1.tag=100;
[self.view addSubview:view1];
//通过tag使tag值为100的view背景变成黑色
[self.view viewWithTag:100].backgorundColor=[UIColor blackColor];

 

15.动画代码块

动画代码块
1.[UIView animationWithDuration:5.0
                animations:^{
                     //code
                }];
2.[UIView animationWithDuration:5.0
                animations:^{
                     //code
                }
                completion:^(BOOL finished){
                     //动画后执行的code
                }];
3.[UIView animationWithDuration:5.0
                delay:2.0 //延时执行
                options:  //动画过度效果 枚举类型
                animations:^{
                     //code
                }
                completion:^(BOOL finished){
                     //动画后执行的code
                }];

 

16.NSUserDefaults明文存储

NSUserDefaults[明文]
//写入数据
NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
[userDefaults setObject:@"123456" forKey:@"password"];
[userDefaults synchronize]; //同步数据到磁盘 非必需
//读取数据
NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
NSString* str=[userDefault stringForKey:@"password"];
NSLog(@"%s",str);

 

17.获取文件目录

App沙盒
每一个App自己使用的独立空间-沙盒
不能跨沙盒访问数据

沙盒的三个子目录
Document 存放长期文件
Library 系统存放文件
tmp 临时文件 App重启时该目录下文件清空

//获取根目录
NSString* homePath=NSHomeDirectory( );

//获取Documents文件夹目录
NSArry* docPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString* documentsPath=docPath[0];

//获取Cache文件夹目录
NSArry* cacPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString* cachePath=cacPath[0];

//获取Library文件夹目录
NSArry* libPath=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString* libraryPath=libPath[0];

//获取tmp目录
NSString* tempPath=NSTemporaryDirectory( );

 

posted @ 2015-12-23 10:53  death3721  阅读(295)  评论(0编辑  收藏  举报