iOS:以前笔记,未整理版。太多了,先放着吧。。。。。。。
1、
-(void)timetick
{
_d = 0;
NSTimer *newtime =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printfdate:) userInfo:@"byL" repeats:YES];
}
-(void)printfdate:(NSTimer*)time1
{
NSLog(@"%d,%@",_d++,time1.userInfo);
}
[newtime invalidate];
[[NSRunLoop currentRunLoop]run];
//初始化观察
[_phone addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
//观察到变化控制
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
NSNumber *num = [change objectForKey:@"new"];
NSLog(@"%@",num);
}
//发送信息
[[NSNotificationCenter defaultCenter]postNotificationName:@"pricechange" object:self userInfo:nil];
//接受信息初始化
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(salephone) name:@"pricechange" object:nil];
//接受到信息做控制
-(void)salephone
//数组
NSArray *DATA_A =@[类,类,类,类,类];
//设置过滤条件
NSPredicate *newpre = [NSPredicate predicateWithFormat:@"age > 29"];
//过滤后保存的数组
NSArray *newarray = [DATA_A filteredArrayUsingPredicate:newpre];
@“name BEGINSWITH 'x' ”
@“name ENDSWITH 'x' ”
@“name CONTAINS 'x' ”
@“age > 29 || age < 20”
@“name like ‘?d*’ ”
2、
sql
====================================================================
创建:
打开:数据库指针、保存地址
sqlite3_open([path UTF8String], &new_sql)
————————————————————————————————————————
创建:数据库指针、创建指令、错误指令
(
NSString *command = @"CREATE TABLE IF NOT EXISTS UserTable (username TEXT primary key,password TEXT,age TEXT)";
)
sqlite3_exec(new_sql, [command UTF8String], NULL, NULL, &new_error)
————————————————————————————————————————
关闭:数据库指针
sqlite3_close(new_sql);
====================================================================
插入:
打开:
同
————————————————————————————————————————
插入指令:
(
NSString *op = @"INSERT INTO UserTable(username,password,age) VALUES (?,?,?)";
)
准备:数据库指针、插入指令、句柄
sqlite3_prepare(new_sql, [op UTF8String], -1, &new_stmt, NULL);
绑定:句柄、位置、数据
sqlite3_bind_text(new_stmt, 1, [name UTF8String], -1, NULL);
下一步:句柄
sqlite3_step(new_stmt);
结束:句柄
sqlite3_finalize(new_stmt);
————————————————————————————————————————
关闭:
同
====================================================================
删除:
打开:
同
————————————————————————————————————————
删除指令:
(
NSString *op = @"DELETE FROM userTable WHERE userName = ?";
)
准备:数据库指针、删除指令、句柄
sqlite3_prepare(new_sql, [op UTF8String], -1, &new_stmt, NULL);
绑定:句柄、位置、数据
sqlite3_bind_text(new_stmt, 1, [name UTF8String], -1, NULL);
下一步:句柄
sqlite3_step(new_stmt);
结束:句柄
sqlite3_finalize(new_stmt);
————————————————————————————————————————
关闭:
同
====================================================================
选择:
打开:
同
————————————————————————————————————————
选择指令:
(
(1)NSString *op = @"SELECT username,password,age From UserTable where username = ?";
(2)NSString *op = @"SELECT username,password,age From UserTable";
)
准备:数据库指针、选择指令、句柄
sqlite3_prepare(new_sql, [op UTF8String], -1, &new_stmt, NULL);
绑定:句柄、位置、数据
(1)sqlite3_bind_text(new_stmt, 1, [selet_name UTF8String], -1, NULL);
下一步:句柄
sqlite3_step(new_stmt);
遍历:
while (result == SQLITE_ROW)
{
char *c_name = (char *)sqlite3_column_text(new_stmt, 0);
char *c_password = (char *)sqlite3_column_text(new_stmt, 1);
char *c_age = (char *)sqlite3_column_text(new_stmt, 2);
NSString *s_name = [NSString stringWithCString:c_name encoding:NSUTF8StringEncoding];
NSString *s_password = [NSString stringWithCString:c_password encoding:NSUTF8StringEncoding];
NSString *s_age = [NSString stringWithCString:c_age encoding:NSUTF8StringEncoding];
NSLog(@"%@,%@,%@",s_name,s_password,s_age);
result = sqlite3_step(new_stmt);
//NSLog(@"%d",new_stmt);
}
结束:句柄
sqlite3_finalize(new_stmt);
————————————————————————————————————————
关闭:
同
====================================================================
插入变体:
更新
@"UPDATE UserTable SET password = ? where username = ?"
选择(2)变体:
排序
@“SELECT * FROM userTable ORDER BY age ASC(DESC)”
3、
4、
int gNumb=0;
全局变量通常用小写g来提示。
重写,父类有声明,不必再声明
[p1 isKindOfClass:[Person class]];
[p1 isMemberOfClass:[Person class]];
[p1 respondsToSelector:@selector(test)];
可变数组 copy 赋值给不可变数组。
-(NSString *)description
{
return [NSString stringWithFormat:@"%@,%lu",_name,_price];
}
==========================================================================
//编码
NSData *new_data = [s_text dataUsingEncoding:NSUTF8StringEncoding];
//解码
NSString *new_string = [[NSString alloc]initWithData:new_data encoding:NSUTF8StringEncoding];
==========================================================================
//沙盒路径
NSHomeDirectory()
//工程目录
[NSBundle mainBundle]
==========================================================================
//弄个文件管理
NSFileManager *new_File = [NSFileManager defaultManager];
//创建文件夹 path要追加文件夹名,不要后缀
[new_File createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&new_error]
//创建文件 path在之前文件夹下追加“xxx.xxx” data要编码
[new_File createFileAtPath:new_path contents:new_data attributes:nil]
//读取文件的信息 返回字典
[new_File attributesOfItemAtPath:new_path error:&new_error]
//读取单个字典的关键词
[new_dic objectForKey:@"NSFileSize"]
==========================================================================
//文件读取
NSData *newData = [fileManager contentsAtPath:filePath];
[[NSString alloc]initWithData:newData encoding:NSUTF8StringEncoding];
or
[[NSString alloc]initWithContentsOfFile:new_path encoding:NSUTF8StringEncoding error:&new_error];
//文件移动(剪切、重命名),要加上文件名和后缀”xxx.xx”
[new_File moveItemAtPath:new_path toPath:ob_add error:&new_error]
//文件复制 也要注意有文件名和后缀“xxx.xx”
[new_File copyItemAtPath:new_path toPath:ob_add_2 error:&new_error]
//文件删除 也要注意有文件名和后缀“xxx.xx”
先判断有无文件
[new_File fileExistsAtPath:ob_add_2]
删除
[new_File removeItemAtPath:ob_add_2 error:&new_error]
==========================================================================
//写入
/设置为写入模式
NSFileHandle *new_handle = [NSFileHandle fileHandleForWritingAtPath:path];
/先转码
NSString *new_string = @"hello,hello,hello,世界";
NSData *new_data = [new_string dataUsingEncoding:NSUTF8StringEncoding];
/再写入
[new_handle writeData:new_data];
//追加
/先找到最后的
[new_handle seekToEndOfFile];
/写入转码后的数据
[new_handle writeData:new_data_2];
//覆盖
/先找到偏移位
[new_handle seekToFileOffset:3];
/写入转码后的数据
[new_handle writeData:new_data_3];
//关闭操作
[new_handle closeFile];
//读取
/设置为读取模式
new_handle = [NSFileHandle fileHandleForReadingAtPath:path];
/读取所有data
NSData *read_data = [new_handle readDataToEndOfFile];
/转成字符串
NSString *read_string = [[NSString alloc]initWithData:read_data encoding:NSUTF8StringEncoding];
/设置为读取模式,否则有问题
new_handle = [NSFileHandle fileHandleForReadingAtPath:path];
/读取前几个数据
read_data = [new_handle readDataOfLength:10];
/转成字符串
ead_string = [[NSString alloc]initWithData:read_data encoding:NSUTF8StringEncoding];
//关闭操作
[new_handle closeFile];
5、
协议
@required
@optional
nonatomic
copy assign
==================================================
.h签协议
<NSCopying>
.m设置要复制的值
- (id)copyWithZone:(nullable NSZone *)zone
{
NSLog(@"复制对象调用了!");
Person *person = [[self class] allocWithZone:zone];
person.name = [_name mutableCopy];
person.age = _age;
person.bookArray = [_bookArray mutableCopy];
return person;
}
调用
Person *person2 = [person1 copy];
==================================================
.h签协议
<NSCoding>
.m设置要复制的值
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeInteger:_age forKey:AGE];
[aCoder encodeObject:_hobby forKey:HOBBY];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
self.name = [aDecoder decodeObjectForKey:NAME];
self.age = [aDecoder decodeIntegerForKey:AGE];
self.hobby = [aDecoder decodeObjectForKey:HOBBY];
}
return self;
}
调用
//地址
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/di8zhangzuoue.txt"];
//归档
[NSKeyedArchiver archiveRootObject:atext toFile:path]
//读取
[NSKeyedUnarchiver unarchiveObjectWithFile:path];
==================================================
单例 共享信息
.m
static OneT *newone = nil;
+(instancetype)shalldata
{
if (newone == nil)
{
newone = [[OneT alloc]init];
newone.data_zone = [NSMutableArray array];
}
return newone;
}
调用:
OneT *one = [OneT shalldata];
OneT *two = [OneT shalldata];
==================================================
NSArray *data = [NSArray arrayWithObjects:@"zhang3",@"li4", nil];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"ceshi83.txt"];
BOOL status = [NSKeyedArchiver archiveRootObject:data toFile:path];
NSLog(@"%@",status?@"成功":@"失败");
NSArray *r_data = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@",r_data);
6、
instancetype:返回与初始化类相同的类型。
-(instancetype)initWith…
{
self=[super init];
if(self)
{
…
}
return self;
}
-(class_A *)initwithone:(int)a other:(int)b
{
self=[super init];
if(self)
{
[self seta:a b:b ] ;
}
return self;
}
+(instancetype)robotWithName:(NSString*)r_name andage:(int)r_age
{
#if 0
return [[self alloc]initWithName:(NSString*)r_name andage:(int)r_age];
#else
Robot *new_R = [[Robot alloc]initWithName:r_name andage:r_age];
return new_R;
#endif
}
@private 私有:只有类定义内部可访问
@protected 保护:只有类本身和子类的定义里可访问
@public 公有:程序的任何位置都可访问
/** xxx */
#progame MARK xxx
[self performSelector:@selector(delaylog:) withObject:@"3秒" afterDelay:2];
[[NSRunLoop currentRunLoop]run];
7、
SET
//初始化
NSSet *set = [[NSSet alloc]initWithObjects:@“_1”,@“_2”,@“_3”,@“_4”,@“_3”, nil];
//可变初始化
NSMutableSet *mSet = [NSMutableSet set];
//可变添加对象
[mSet addObject:numobject];
//建个数组
NSArray *array = [NSArray arrayWithObjects:@“_3”,@“_4”,@“_5”, nil];
//取数组的对象初始化
NSSet *newSet = [NSSet setWithArray:array];
//又把set的对象给数组,自动消除重复
NSArray *newArray = [newSet allObjects];
//打印
NSLog(@"%ld",[newSet count]);
//任意取! 但不保证随机!
NSLog(@"%@",[set anyObject]);
//是否等价
[set isEqualToSet:newSet]
//是否包含
[newSet isSubsetOfSet:set]
ENUM
//将set的值给枚举
NSEnumerator *enumtor = [set objectEnumerator];
//将枚举里的对象一一打印
for (NSObject* obj in enumtor)
{
NSLog(@"-->%@",obj);
}
8、
日期时间
//美国的时间
NSDate *date = [[NSDate alloc]init];
//时区
NSTimeZone *myZone = [NSTimeZone systemTimeZone];
//算时差 加上时差
NSInteger interValTimer = [myZone secondsFromGMTForDate:date];
NSDate *localDate = [date dateByAddingTimeInterval:interValTimer];
NSLog(@"%@",localDate);
//明天
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];
//昨天
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:-ADAY];
NSLog(@"date2 = %@",date2);
//1970年
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:0];
NSLog(@"%@",date2);
//参考日期2001年
NSDate *date3 = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
NSLog(@"%@",date3);
//nsdate -> nsstring 类型转换
NSDate *date1 = [NSDate date];
1.
NSString *date1str = date1.description;//美国的时间
2
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc]init];
2.1
[dateFormat1 setDateFormat:@"yyyy年MM月dd日 EEEE HH mm ss zz"];
2.2
[dateFormat1 setDateStyle:NSDateFormatterShortStyle];
[dateFormat1 setTimeStyle:NSDateFormatterMediumStyle];
NSString *datestr2 = [dateFormat1 stringFromDate:date1];
NSLog(@"datestr2 = %@",datestr2);
//获取所有时区的名字
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
//新建一个时区
NSTimeZone *newZone = [NSTimeZone timeZoneWithName:@"Pacific/Fiji"];
//新建一个时间格式
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc]init];
//设置该时区
[dateFormat2 setTimeZone:newZone];
//设置时间格式
[dateFormat2 setDateFormat:@"yyyy年MM月dd日 EEEE HH:mm:ss zz"];
//打印
NSString *dateString = [dateFormat2 stringFromDate:[NSDate date]];
NSLog(@"dateString = %@",dateString);
//字符串转date
NSString *dateStr4 = @"2016年07月27日 星期三 20:16:10 GMT+12";
NSDate *date4 = [dateFormat2 dateFromString:dateStr4];
NSLog(@"%@",date4);
NSRange newrange = NSMakeRange(1,5);
NSValue *newvalue = [NSValue valueWithRange:newrange];
NSLog(@"%@",newvalue);
NSArray *newarray = [NSArray arrayWithObjects:newvalue, nil];
NSLog(@"%@",newarray);
NSRange newrange2 = [newvalue rangeValue];
NSLog(@"%lu,%lu",newrange2.location,newrange2.length);
//封装自定义的结构体
struct MyPoint
{
int x;
int y;
};
struct MyPoint mypoint;
mypoint.x = 10;
mypoint.y = 100;
NSValue *val2 = [NSValue value:&mypoint withObjCType:@encode(struct MyPoint)];
NSLog(@"%@",val2);
struct MyPoint mypoint2;
[val2 getValue:&mypoint2];
NSLog(@"mypoint2.x = %d,mypoint2.y = %d",mypoint2.x,mypoint2.y);
9、
@interface class_A:NSObject
…
@end
@implementation class_A
…
@end
@property int x;
@synthesize x;
[MyA setNumb:5];即使实例变量是小写,这个set后也要大写
n=[MyA numb];
[A B] 等价 A.B
[self 该.m文件的方法],找不到再去父类找
与文件.h.m同名
@interface class_A:NSObject
…
@end
@interface class_B:class_A
…
@ens
继承里,class_B里的方法的可以用
[self A的方法]
[self A的变量]
需要某文件的某些方法,可以用
@class xxx.h
小
如果xxx.h的某些方法访问不了,如init,还是要
#import xxx.h
大
重复包含的,其中一个.h可以用@class xxx(不用写.h),对应.m要#import xxx.h
同名方法优先使用class_B的方法
同名的方法,会自动判断[A set_value:(int)x]的类,如判断出A
id x;
x=任意变量、class类
@try
{
…
}
@catch
{
…
}
@finally
{
…
}
还有的@throw
10、
字符串:
字符串的创建
对象方法:
[[NSString alloc]init];
[[NSString alloc]initWithString:string];
[[NSString alloc]initWithFormat:@"%@",string1];
类方法:
[NSString stringWithString:string];
[NSString stringWithFormat:@"%@",string2];
字符串格式化拼接
[NSString stringWithFormat:@"%@%@",string3,string4];
字符串比较
[string3 isEqualToString:string4];
[string3 caseInsensitiveCompare:string4];
[string3 compare:string4]
字符串长度
[string length];
string.length;
字符串大小写变化
[string uppercaseString];
[string lowercaseString];
[string capitalizedString];
字符串追加
[string4 stringByAppendingString:string3];
字符串查找
[string rangeOfString:@"world"];
NSNotFound
[string hasPrefix:@“www”];
[string hasSuffix:@“com”];
字符串截取
[string substringFromIndex:2];
[string substringToIndex:5];
[string substringWithRange:range];
字符串跟基本数据类型转换
[NSString stringWithFormat:@"%d",a];
[NSString stringWithFormat:@"%f",b];
[NSString stringWithFormat:@"%c",c];
[strnum1 intValue];
[strnum2 floatValue];
const char *cc = [strchar UTF8String];
字符串取个元素
[newstring characterAtIndex:3]
字符串是否包含
[mString containsString:@"hello"];
可变字符串的创建
[[NSMutableString alloc]initWithString:string];
[[NSMutableString alloc]initWithFormat:@"%@",string];
[NSMutableString stringWithString:string];
[NSMutableString stringWithFormat:@"%@",string];
可变字符串的替换
[mString replaceCharactersInRange:NSMakeRange(2,2) withString:@"xxx"];
可变字符串的插入
[mString insertString:@"aaa" atIndex:1];
可变字符串的删除
[mString deleteCharactersInRange:NSMakeRange(1, 3)];
可变字符串的追加
[S_1 appendString:@"QAZ"];
[S_1 appendFormat:@"%@",S_1];
11、
字典的创建
NSDictionary *dic = [[NSDictionary alloc]init];
//dic = @{key:value,...};
dic = @{
@"name":@"xiaoming",
@"age":@"18",
@"sex":@"男",
@"name1":@"xiaoming"
};
对象方法:
//dic2 = @{value:key,...};
NSDictionary *dic2 = [[NSDictionary alloc]initWithObjectsAndKeys:@"xiaohong",@"name",@"20",@"age",@"男",@"sex",@"12",@"20",@"aaa",@"bbb", nil];
NSDictionary *dic3 = [[NSDictionary alloc]initWithDictionary:dic2];
类方法:
NSDictionary *dic4 = [NSDictionary dictionaryWithDictionary:dic3];
字典的长度
字典根据key获取value
[dic objectForKey:@"age"]
dic[@"age"]
字典取出所有的key
NSArray *keyArray = [dic allKeys];
字典取出所有的value
NSArray *valueArray = [dic allValues];
可变字典的创建
NSMutableDictionary *mDic1 = [NSMutableDictionary dictionary];
类方法:
NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"xiaoming",@"name",@"19",@"age",@"男",@"sex", nil];
可变字典添加元素
[mDic setObject:@"80kg" forKey:@"weight"];
可变字典删除元素
[mDic removeObjectForKey:@"age"];
[mDic removeObjectsForKeys:array];
可变字典删除所有元素
[mDic removeAllObjects];
可变字典遍历
for (NSString *key in mDic)
{
NSLog(@"%@",mDic[key]);
}
存储
NSString *path = @"/Users/etcxm/test.plist";
[dic writeToFile:path atomically:YES];
NSArray *A_data_R = [NSArray array];
A_data_R = [NSArray arrayWithContentsOfFile:S_add];
12、
数组的创建
NSArray *array1 = [[NSArray alloc]init];
array1 = @[@"here",@"is",@"etcxm"];
对象方法:
NSArray *array6 = [[NSArray alloc]initWithObjects:array1,array5, nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:@"here",@"is",@"china", nil];
NSArray *array3 = [[NSArray alloc]initWithArray:array1];
类方法:
NSArray *array4 = [NSArray arrayWithObject:@"hello"];
NSArray *array5 = [NSArray arrayWithObjects:@"here",@"is",@"china", nil];
NSArray *array6 = [NSArray arrayWithArray:array1];
数组取下标元素
array5[2];
[array5 objectAtIndex:2];
数组的长度
array5.count
[array5 count]
数组是否包含某个元素
[array10 containsObject:@"hello”];
数组通过元素获取下标
[array10 indexOfObject:@"1123”];
NSNotFound
数组连接成字符串,字符串分割成数组
NSString *string = [array1 componentsJoinedByString:@" "];
NSArray *array2 = [string componentsSeparatedByString:@"i"];
数组访问最后一个元素
[array1 lastObject];
[array1 firstObject];
数组遍历
for (NSString *str in array1)
{
NSLog(@"->%@",str);
}
数组追加元素
NSArray *array3 = [array1 arrayByAddingObject:@"hello"];
NSArray *array4 = [array1 arrayByAddingObject:array3];
NSArray *array5 = [array1 arrayByAddingObjectsFromArray:array3];
可变数组的创建
NSMutableArray *mArray = [[NSMutableArray alloc]initWithObjects:@"hello",@"world",@"china", nil];
可变数组添加元素
[mArray addObject:@"American"];
NSArray *array = [[NSArray alloc]initWithObjects:@"hi",@"hei", nil];
[mArray addObjectsFromArray:array];
可变数组删除元素
[mArray removeAllObjects];
[mArray3 removeObject:@"here"];
[mArray3 removeObjectAtIndex:3];
[mArray3 removeLastObject];
[mArray3 removeObjectsInArray:arraytest];
[mArray3 removeObjectsAtIndexes:set1];
[mArray3 removeObject:@"here" inRange:NSMakeRange(0, 3)];
[mArray3 removeObjectsInRange:NSMakeRange(1, 4)];
可变数组交换位置
[mArray3 exchangeObjectAtIndex:0 withObjectAtIndex:3];
可变数组替换
[mArray3 replaceObjectAtIndex:0 withObject:@"objxxx"];
可变数组插入
[mArray3 insertObject:@"iiiii" atIndex:1];
可变数组遍历
int i=0;
for (NSString *str in mArray)
{
NSLog(@"%@",str);
NSLog(@"%d",i++);
}