OC|Objective-C笔记大全

1.0 Basic Operations

srand((unsigned)time(0)); //种种子 int index = arc4random() % poker.allCads.count; //不需要种子取随机数 [p retain]; //查看引用计数值 __weak => [p release]; p = nil; //不能分配空间,马上释放

1.1 CopyWithZone
- (id)copyWithZone:(NSZone *)zone { Integer *i = [[Integer allocWithzone:zone] initWithInteger:self.ingeger]; return i; }

1.2 The judgement of class
- [square isKindOfClass:[TRSquare class]] == YES; //判断是否为子类对象 - [square isMemberOfClass:[TRSquare class]] == YES; //判断是否为成员对象 - [square isSubClassOfClass:[TRSquare class]] == YES; //判断是否为子类 - SEL sel = @selector(study) - [Student instancesRespondToSelector:sel] == YES //判断类中是否有指定方法 - [stu respondsToSelector:@selector(learn)] == YES //判断对象能否调用指定方法 - [stu performSelector:sel] => [stu study] //执行方法

1.3 Protocol
- Protocol *p = @protocol(NSCopying); - [Student conformsToProtocol:p] == YES //判断是否采纳指定协议

1.4 NSString
- [str substringToIndex:3]; //截取头,截取从下标0到3的字符 - [str substringFromIndex:10] //截取尾,截取下标10以后的字符 - [str substngWithRange:NSMakeRange(4,4)]; //范围截取,从下标4开始截取4个字符 - str = [str1 stringByAppendingString:str2]; //字符串拼接 - str = [str1 stringByAppendingFormat:@"%@%d",str2,i]; //格式化追加 - str = [str1 stringByReplacingCharactersInRange:NSMakeRange(4,10) withString:@"tedu"]; //指定范围替换 - str = [NSString stringWithContentOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; //文件内容初始化字符串 - str = [NSString stringWithCString:CString encoding:NSASCIIStringEncoding]; //C字符串转为OC字符串

1.5 NSMutableString
- [NSMutableString stringWithcapacity:100]; //预估值初始化 - [NSMutableString stringWithString:@"string"]; //标准化初始化 - [NSMutableString stringWithFormat:@"age:%d",age]; //标准格式化 - [str appendString:@"The String"]; //追加 - [str appendFormat:@"have %lucharacters.",str.length]; //格式化追加 - NSRange range = [str rangeOfString:@"Objective-"]; - [str deleteCharactersInRange:range]; //指定范围删除 - [str replaceCharactersInRange:[str rangeOfString:@"a"] withString:@"another"]; //指定字符串替换

1.6 Packaging & Unpackaging
- NSNumber *i = [NSNumber numberWithInt:a]; //封装 - int b = [i intValue]; //拆封- NSNumber *c = [NSNumber numberWithChar:ch]; - char ch1 = [c charValue]; - NSNumber *d1 = [NSNumber numberWithDouble:d]; - double d2 = [d1 doubleValue]; - NSNumber *f1 = [NSNumber numberWithFloat:f]; - float f2 = [f1 floatValue]; - NSNumber *b2 = [NSNumber numberWithBool:b1]; - BOOL b3 = [b2 boolValue];

1.7 NSValue
typedef struct { int x; int y; }TRPoint; typedef struct { char ch; double d; }TRMyData; int main(int argc, const char * argv[]) { @autoreleasepool { TRPoint p; p.x = 10; //0xA p.y = 15; //0xF NSValue *value = https://www.it610.com/article/[NSValue valueWithBytes:&p objCType:@encode(TRPoint)]; //封装 NSLog(@"%@", value); TRPoint p1; [value getValue:&p1]; //拆封 NSLog(@"(%d,%d)", p1.x, p1.y); TRMyData data = https://www.it610.com/article/{'a', 3.14}; NSValue *md = [NSValue valueWithBytes:&data objCType:@encode(TRMyData)]; TRMyData data1; [md getValue:&data1]; NSLog(@"%c,%g", data1.ch, data1.d); } return 0; }

1.8 Description
- NSLog(@"%@", teacher); //输出teacher对象,自动调用重写的description方法-(NSString *)description { return [NSString stringWithFormat:@"姓名:%@,课程:%@", self.name, self.course]; }

1.9 NSData
#获取世界标准时间 NSDate *date = [NSDate date]; #获取本地时间方法一 NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSInteger integer = [zone secondsFromGMTForDate:[NSDate date]]; NSDate *localDate = [[NSDate date] dateByAddingTimeInterval:integer]; #获取本地时间方法二 NSDate *localDate = [[NSDate date] dateByAddingTimeInterval:8*3600]; #获取本地时间方法三 NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:8*3600]; #格式化本地时间方法 NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init]; dateformatter.dateFormat = @"yyyy-MM-dd hh:mm:ss"; //hh:12小时制,HH:24小时制 NSString *str = [dateformatter stringFromDate:date]; #从1970年1月1日至今所经历的秒数 NSTimeInterval seconds = [date timeIntervalSince1970]; #从指定时间到当前所经历的秒数 NSTimeInterval seconds = [date timeIntervalSinceNow]; #两个指定时间之间的秒数 NSTimeInterval seconds = [time1 timeIntervalSinceDate:time2]; #时间对比 NSDate *early = [time1 earlierDate:time2]; //较早 NSDate *later = [time1 laterDate:time2]; //较晚 [time1 isEqualToDate:time2] == YES //判断两个时间是否相同#输入一个身份证号码判断年龄 scanf("%s", str); NSString *ID = [NSString stringWithFormat:@"%s", str]; NSString *birthdayYear = [ID substringWithRange:NSMakeRange(6, 4)]; NSDate *date = [NSDate date]; NSDateFormatter *f = [[NSDateFormatter alloc] init]; f.dateFormat = @"yyyy"; NSString *thisYear = [f stringFromDate:date]; int age = [thisYear intValue] - [birthdayYear intValue]; NSLog(@"年龄是:%d", age);

2.0 NSArray
- NSArray *array3 = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; //创建数组包含多个元素 - NSArray *array4 = @[@"one", @"two", @"three"]; //优化方法,最常用的方法 - NSArray *array5 = [NSArray arrayWithArray:array4]; //副本 - NSUInteger index = [array4 indexOfObject:@"one"]; //根据元素值求在数组中的下标 - NSArray *stu = @[stu1, stu2, stu3]; NSArray *copied = [[NSArray alloc] initWithArray:stu copyItems:NO]; //NO是引用计数拷贝 NSArray *deepCopied = [[NSArray alloc] initWithArray:stu copyItems:YES]; //YES深拷贝

2.1 NSMutableArray
  • ###创建
- NSMutableArray *array1 = [NSMutableArray array]; //空数组,有意义 - NSMutableArray *array2 = [NSMutableArray arrayWithCapacity:100]; //预估值 - NSMutableArray *array3 = @[@"one", @"two", @"three"]; //arra3会退化成不可变数组 - NSMutableArray *array4 = [NSMutableArray arrayWithObjects:@"one", @"two", @"three"];

  • ###添加
- [array4 addObject:@"four"]; //在数组的最后添加一个元素 - [array4 insertObject:@"five" atIndex:1]; //在任意下标插入

  • ###删除
- [array4 removeLastObject]; //最后一个 - [array4 removeObject:@"six"]; //指定元素 - [array4 removeObjectAtIndex:2]; //指定下标 - [array4 removeObjectsInRange:NSMakeRange(3, 2)]; //指定范围 - [array4 removeObjectsInArray:@[@"one", @"three"]]; //指定数组 - [array4 removeAllObjects]; //清空数组

2.2 NSSet
int main(int argc, const char * argv[]) { @autoreleasepool { NSSet *set1 = [NSSet setWithObjects:@"one", @"two", @"three", nil]; //遍历 NSLog(@"%@", set1); NSArray *array = [set1 allObjects]; for (int i = 0; i < array.count; i++) { NSLog(@"%@", array[i]); } for (NSString *str in set1) { NSLog(@"%@", str); } NSEnumerator *e = [set1 objectEnumerator]; //枚举器遍历 NSSet *str; while (str = [e nextObject]) { NSLog(@"%@", str); } } return 0; }

2.3 NSMutableSet
int main(int argc, const char * argv[]) { @autoreleasepool { //创建 NSMutableSet *set1 = [NSMutableSet set]; //空集合,有意义 NSMutableSet *set2 = [NSMutableSet setWithCapacity:100]; //预估值 NSMutableSet *set3 = [NSMutableSet setWithObjects:@"one", @"two", @"three", nil]; //添加 [set3 addObject:@"four"]; //一个 NSLog(@"%@", set3); NSArray *added = @[@"five", @"six"]; [set3 addObjectsFromArray:added]; //多个 NSLog(@"%@", set3); //删除 [set3 removeObject:@"three"]; //指定元素 NSLog(@"%@", set3); [set3 removeAllObjects]; //清空集合 NSLog(@"%lu", set3.count); //交集 NSArray *added1 = @[@"one", @"two", @"three"]; [set3 addObjectsFromArray:added1]; NSArray *added2 = @[@"one", @"four", @"three"]; [set2 addObjectsFromArray:added2]; [set3 intersectSet:set2]; //结果被放回set3 NSLog(@"%@", set3); //并集 [set3 unionSet:set2]; NSLog(@"%@", set3); //从一个集合A中删除另一个集合B中的元素 [set2 removeAllObjects]; [set2 addObjectsFromArray:added1]; [set3 removeAllObjects]; [set3 addObjectsFromArray:added2]; [set3 minusSet:set2]; NSLog(@"%@", set3); } return 0; }

2.4 NSDictionary
int main(int argc, const char * argv[]) { @autoreleasepool { //创建 NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"one", @"1", @"two", @"2", @"three", @"3", nil]; //标准 NSDictionary *dict2 = @{@"1":@"one", @"2":@"two", @"3":@"three"}; //优化方法 NSArray *objects = @[@"one", @"two", @"three"]; NSArray *keys = @[@"1", @"2", @"3"]; NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; //由数组 NSDictionary *dict4 = [NSDictionary dictionaryWithDictionary:dict3]; //副本//求键值对的个数 NSLog(@"%lu", dict4.count); //获取字典中的所有值 NSArray *objects1 = [dict4 allValues]; //获取字典中的所有关键字 NSArray *keys1 = [dict4 allKeys]; //根据一个关键字来查找一个值 NSString *str = [dict4 objectForKey:@"1"]; //标准 str = dict4[@"2"]; //优化方法//根据多个关键字来找多个值 NSArray *keys2 = @[@"1", @"4"]; NSArray *objects2 = [dict4 objectsForKeys:keys2 notFoundMarker:@"no object"]; //通过值找到对应的关键字 NSArray *keys3 = [dict4 allKeysForObject:@"three"]; //排序 TRStudent *stu1 = [[TRStudent alloc] initWithName:@"张三" andAge:18]; TRStudent *stu2 = [[TRStudent alloc] initWithName:@"李四" andAge:20]; TRStudent *stu3 = [[TRStudent alloc] initWithName:@"刘五" andAge:19]; NSDictionary *dict5 = @{@"1":stu1, @"2":stu2, @"3":stu3}; NSArray *sorted = [dict5 keysSortedByValueUsingSelector:@selector(compareAge:)]; for (NSArray *key in sorted) { NSLog(@"%@ - %@", key, dict5[key]); } NSArray *sortedName = [dict5 keysSortedByValueUsingSelector:@selector(compareName:)]; for (NSArray *key in sortedName) { NSLog(@"%@ - %@", key, dict5[key]); }//遍历 NSArray *keys4 = [dict5 allKeys]; for (NSString *key in keys4) { NSLog(@"%@-%@", key, dict5[key]); }NSEnumerator *e = [dict5 keyEnumerator]; //关键字枚举器 NSString *key; while (key = [e nextObject]) { NSLog(@"%@-%@", key, dict5[key]); }NSEnumerator *e1 = [dict5 objectEnumerator]; //值枚举器 TRStudent *stu; while (stu = [e1 nextObject]) { NSLog(@"%@", stu); }for (NSString *key in dict5)//OC循环 { NSLog(@"%@-%@", key, dict5[key]); }//向文件中写 [dict2 writeToFile:@"/Users/tarena/Desktop/dict.plist" atomically:YES]; //从文件中读 NSDictionary *dict6 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/tarena/Desktop/dict.plist"]; } return 0; }

2.5 NSMutableDictionary
int main(int argc, const char * argv[]) { @autoreleasepool { //创建 NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; //空字典,有意义 NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithCapacity:100]; //预估值 NSMutableDictionary *dict3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"one", @"1", @"two", @"2", @"three", @"3", nil]; //标准 NSMutableDictionary *dict4 = @{@"1":@"one", @"2":@"two", @"3":@"three"}; //退化成不可变字典//添加 [dict3 setValue:@"four" forKey:@"4"]; //一个 NSLog(@"%@", dict3); NSDictionary *added = @{@"5":@"five", @"6":@"six", @"7":@"seven"}; [dict3 addEntriesFromDictionary:added]; //多个 NSLog(@"%@", dict3); //覆盖 NSDictionary *dict5 = @{@"1":@"aaa", @"2":@"bbb", @"3":@"ccc"}; NSMutableDictionary *dict6 = [NSMutableDictionary dictionaryWithCapacity:100]; [dict6 addEntriesFromDictionary:dict5]; NSDictionary *dict7 = @{@"1":@"one", @"2":@"two", @"3":@"three"}; [dict6 setDictionary:dict7]; NSLog(@"%@", dict6); //删除 [dict6 removeObjectForKey:@"1"]; //指定关键字 NSLog(@"%@", dict6); NSArray *keys = @[@"2", @"3"]; [dict6 removeObjectsForKeys:keys]; //多个 NSLog(@"%@", dict6); [dict6 removeAllObjects]; //清空字典 NSLog(@"%lu", dict6.count); } return 0; }

2.6 Block
int a = 10; void (^myBlock)(void) = ^void(void){ NSLog(@"Block被执行了"); }; double (^myBlock1)(int, int) = ^double(int a, int b){return b ? a * 1.0 / b : 0; }; typedef void(^BlockType)(void); typedef double(^BlockType1)(int, int); int g_i = 10; int main(int argc, const char * argv[]) { @autoreleasepool {myBlock(); NSLog(@"%g", myBlock1(2, 3)); BlockType b1; b1 = ^void(void){ NSLog(@"用Block类型定义的变量"); }; b1(); BlockType1 b2 = ^double(int a, int b){ return b ? a * 1.0 / b : 0; }; NSLog(@"%g", b2(2, 5)); //Block与全局变量 BlockType1 b3 = ^double(int a, int b){ NSLog(@"%d", g_i); //可以读取全局变量中的值 g_i = 20; NSLog(@"%d", g_i); //可以对全局变量进行赋值return g_i + a + b; }; NSLog(@"%g", b3(2, 3)); //Block与局部变量 int i2 = 30; __block int i3 = 50; BlockType b4 = ^void(void){ NSLog(@"%d", i2); //可以读取局部变量中的值 //i2 = 40; //不可以对局部变量进行赋值 i3 = 60; //加block关键字后,可以对局部变量进行赋值 NSLog(@"%d", i3); }; b4(); //与数组 NSNumber *a1 = [NSNumber numberWithInt:10]; NSNumber *a2 = [NSNumber numberWithInt:8]; NSNumber *a3 = [NSNumber numberWithInt:20]; NSNumber *a4 = [NSNumber numberWithInt:2]; NSNumber *a5 = [NSNumber numberWithInt:15]; NSArray *num = @[a1, a2, a3, a4, a5]; NSComparisonResult (^compareInt)(id, id) = ^NSComparisonResult(id obj1, id obj2){ NSNumber *a1 = obj1; NSNumber *a2 = obj2; int i1 = [a1 intValue]; int i2 = [a2 intValue]; if (i1 < i2) { return NSOrderedAscending; } else if (i1 > i2) { return NSOrderedDescending; } else { return NSOrderedSame; } }; NSArray *sorted = [num sortedArrayUsingComparator:compareInt]; NSLog(@"%@", sorted); NSArray *strings = @[@"one", @"two", @"three"]; sorted = [strings sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){ NSString *str1 = obj1; NSString *str2 = obj2; return [str1 compare:str2]; }]; NSLog(@"%@", sorted); //与字典 NSDictionary *dict = @{@"1":@"one", @"2":@"two", @"3":@"three"}; sorted = [dict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSString *str1 = obj1; NSString *str2 = obj2; return [str1 compare:str2]; }]; for (NSString *key in sorted) { NSLog(@"%@-%@", key, dict[key]); }TRMyClass *myC = [[TRMyClass alloc] init]; [myC method:^void(void){ NSLog(@"Block做函数参数"); }]; [myC method:^void(void){ NSLog(@"多态了"); }]; [myC getBlock](); myC.block = ^void(void){ NSLog(@"Block作属性"); }; myC.block(); [myC method1:^double(int a, int b){ return a + b; }]; [myC method1:^double(int a, int b){ return a * b; }]; NSLog(@"%g", [myC getBlock1](2, 7)); myC.block1 = ^double(int a, int b) { return a + b; }; NSLog(@"%g", myC.block1(2, 3)); myC.block1 = ^double(int a, int b) { return a * b; }; NSLog(@"%g", myC.block1(2, 3)); } return 0; }

@implementation TRMyClass -(void)method { NSLog(@"method被执行了"); } -(void)method:(MyBlock2)b { b(); //回调 } -(MyBlock2)getBlock { MyBlock2 b = ^void(void){ NSLog(@"Block作函数返回值"); }; return b; } -(void)method1:(MyBlock3)b { NSLog(@"%g", b(2, 3)); } -(MyBlock3)getBlock1 { return ^double(int a, int b){ return a * 1.0 / b; }; } @end

2.7 KVC
TRDept *dept2 = [[TRDept alloc]init]; NSMutableDictionary *deptdata = https://www.it610.com/article/[NSMutableDictionary dictionary]; deptdata[@"name"] = @"test2"; deptdata[@"emps"] = @[ed, ee, ef,ed,ee,ef]; // KVC [dept2 setValuesForKeysWithDictionary:deptdata];

2.8 NSBundle
  • 从文件获取内容到数组
NSString *fullpath = [[NSBundle mainBundle] pathForResource:@"dept_emps.plist" ofType:nil]; NSArray *dataArray = [NSArray arrayWithContentsOfFile:fullpath]; NSLog(@"%@",dataArray);

    推荐阅读