OC常用数据类型大全解
UI基础
OC常用数据类型
Block
Block封装了一段代码,可以在任何时候执行
Block可以作为函数参数或者函数的返回值,而其本身又可以带输入参数或返回值。它和传统的函数指针很类似,但是有区别:block是inline(内联函数)的,并且默认情况下它对局部变量是只读的
苹果官方建议尽量多用block。在多线程、异步任务、集合遍历、集合排序、动画转场用的很多
Blocks的定义
Blocks的定义:
int (^MySum)(int, int) = ^(int a, int b) {
return a+b;
};
定义了一个叫MySum的blocks对象,它带有两个int参数,返回int。等式右边就是blocks的具体实现
Block可以访问局部变量,但是不能修改。
int sum = 10;
int (^MyBlock)(int) = ^(int num) {
sum++;//编译报错
return num * sum;
};
如果要修改就要加关键字:__block
__block int sum = 10;
Blocks和函数指针对比
int (*myFn)();
int (^MyBlocks)(int,int);
(*myFn)(10, 20);
MyBlocks(10, 20);
Blocks的赋值
在声明的同时定义变量,然后赋值
int
(^MySum)(int,int) = ^(int a,int b) {
return a + b;
};
也可先用typedef先声明类型,再定义变量进行赋值
typedef
int (^MySum)(int,int);
MySum
sum = ^(int a,int b) {
return a + b;
};
Foundation框架
正如其名,Foundation框架是其他所有iOS框架的基础
Foundation框架包含了很多开发中常用的数据类型:
#import <Foundation/Foundation.h>
NSRange
在Foundation/NSRange.h中对NSRange的定义
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
}
NSRange;
//
typedef unsigned long NSUInteger;
这个结构体用来表示事物的一个范围,通常是字符串里的字符范围或者数组里的元素范围
location表示该范围的起始位置
length表示该范围内所含的元素个数
比如”I
love objective-c”中的”obj”可以用location为7,length为3的范围来表示
NSRange
有3种方式创建一个NSRange变量
第1种:直接给成员赋值
NSRange
range;
range.location
= 7;
range.length
= 3;
第2种:应用C语言的聚合结构赋值机制
NSRange
range = {7, 3};
或者
NSRange range = {.location = 7,.length = 3};
第3种:Foundation框架提供的一个快捷函数NSMakeRange
NSRange
range = NSMakeRange(7,3);
NSPoint\CGPoint
在Foundation/NSGeometry.h中对NSPoint的定义
typedef
CGPoint NSPoint;
在CoreGraphics/CGGeometry.h中对CGPoint的相关定义
struct
CGPoint {
CGFloat x;
CGFloat y;
};
typedef
struct CGPoint CGPoint;
//
#define CGFLOAT_TYPE double
//
typedef
CGFLOAT_TYPE CGFloat;
NSPoint和CGPoint是等价的
这个结构体代表的是平面中的一个点(x,
y)
NSPoint\CGPoint
Foundation框架提供了一个NSMakePoint()创建NSPoint
NSPoint
point = NSMakePoint(10, 20);
或者
CGPoint
point = NSMakePoint(10, 20);
在CoreGraphics框架中也提供了CGPointMake()创建一个NSPoint(CGPoint)
NSPoint
point = CGPointMake(10, 20);
或者
CGPoint
point = CGPointMake(10, 20);
NSSize\CGSize
在Foundation/NSGeometry.h中对NSSize的定义
typedef CGSize NSSize;
在CoreGraphics/CGGeometry.h中对CGSize的相关定义
struct CGSize {
CGFloat width;
CGFloat height;
};
typedef struct CGSize CGSize;
这个结构体用来存储宽度和高度
可以利用NSMakeSize()和CGSizeMake()创建CGSize
NSRect\CGRect
在Foundation/NSGeometry.h中对NSRect的定义
typedef CGRect NSRect;
在CoreGraphics/CGGeometry.h中对CGRect的相关定义
struct CGRect {
CGPoint origin; // 矩形左上角坐标
CGSize size; // 矩形的宽度和高度
};
typedef struct CGRect CGRect;
这个结构体用来存储位置和宽高
可以利用NSMakeRect()和CGRectMake()创建CGRect
NSString的创建
创建常量字符串
NSString
*string = @"This is a String!";
通过字符串创建字符串
[[NSString alloc] initWithString:@"This
is a String!"];
// 或者[[NSString alloc] initWithFormat:@"My
age is %i",
17];
用标准c创建字符串
char *cString =
"这是一串中文";
[[NSString alloc] initWithCString:cString encoding:NSUTF8StringEncoding];
或者 [[NSString alloc] initWithUTF8String:cString];
// 字符串编码可以在NSString.h中查阅
NSString的创建
从文件中读取字符串
NSError
*error = nil; // 用来记录错误信息
NSString *path =
@"/Users/apple/Desktop/test.txt"; // 文件路径
NSString
*string = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding
error:&error];
if (error)
{ // 文件读取失败
// 得到"通俗易懂"的错误信息
NSString *desc = [error localizedDescription];
NSLog(@"\n文件读取失败,错误信息如下:\n%@",
desc);
}
else { // 文件读取成功
NSLog(@"\n文件读取成功,内容如下:\n%@",
string);
}
// 将中文字符编码转为NSStringEncoding格式的编码
//
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(
kCFStringEncodingGB_18030_2000);
NSString的创建
从一个Url读取字符串
NSError
*error = nil; // 用来记录错误信息
NSURL
*url = [NSURL URLWithString:@"http://www.baidu.com"];
NSString
*string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:nil];
if (error)
{ // 读取失败
// 得到"通俗易懂"的错误信息
NSString *desc = [error localizedDescription];
NSLog(@“\n读取失败,错误信息如下:\n%@",
desc);
}
else { // 读取成功
NSLog(@“\n读取成功,内容如下:\n%@",
string);
}
NSString的创建
还有一些静态方法(都是autorelease的)
[NSString
stringWithUTF8String:"12345"];
[NSString
stringWithFormat:@"My
age is %i", 27];
[NSString
stringWithCString:"12345"
encoding:NSUTF8StringEncoding];
NSString
*path = @"/Users/apple/Desktop/test.txt”;
[NSString
stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
NSURL
*url = [NSURL URLWithString:@"http://www.baidu.com"];
NSString
*string = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:nil];
NSString的导出
将字符串写入文件
NSString
*string = @"我是字符串";
NSString *path =
@"/Users/apple/Desktop/abc.txt";
[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
或者
NSString *urlPath =
@"file:///Users/apple/Desktop/abc.txt";
NSURL *url = [NSURL URLWithString:urlPath];
[string writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString大小写处理
-
(NSString *)uppercaseString
全部转为大写字母
-
(NSString *)lowercaseString
全部转为小写字母
-
(NSString *)capitalizedString
首字母变大写,其他字母都变小写
NSString的比较
-
(BOOL)isEqualToString:(NSString *)aString
比较两个字符串的内容是否相同,相同就返回YES,不同则返回NO
-
(NSComparisonResult)compare:(NSString *)string
逐个字符地进行比较,返回NSComparisonResult来显示比较结果.
NSComparisonResult是一个枚举,有3个值:
NSOrderedAscending
= -1L, NSOrderedSame, NSOrderedDescending
如果左侧大于右侧,返回NSOrderedDescending,
如果左侧小于右侧,返回NSOrderedAscending,
否则返回NSOrderedSame
-
(NSComparisonResult)caseInsensitiveCompare:(NSString *)string
忽略大小写进行比较,返回值与compare:一致
NSString中搜索字符串
-
(BOOL)hasPrefix:(NSString *)aString
是否以aString开头
-
(BOOL)hasSuffix:(NSString *)aString
是否以aString结尾
-
(NSRange)rangeOfString:(NSString *)aString
检查是否包含了aString,如果包含,就返回aString的位置,如果不包含,NSRange的location为-1,length为0
-
(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
可以传递一个mask参数,改变搜索方式
比如NSStringCompareOptions为NSBackwardsSearch表示从尾部开始搜索
-
(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
range:(NSRange)searchRange
还可以用searchRange指定搜索范围
NSString的截取
-
(NSString *)substringFromIndex:(NSUInteger)from
从指定位置from开始(包括指定位置的字符)到尾部
-
(NSString *)substringToIndex:(NSUInteger)to
从字符串的开头一直截取到指定的位置to,但不包括该位置的字符
-
(NSString *)substringWithRange:(NSRange)range
按照所给出的NSRange从字符串中截取子串
-
(NSArray *)componentsSeparatedByString:(NSString *)separator
用separator为分隔符截取子串,返回一个装着所有子串的集合NSArray
NSString与路径
+
(NSString *)pathWithComponents:(NSArray *)components
将components中的字符串按顺序拼成一个路径
-
(NSArray *)pathComponents
将一个路径分解成一个装着每一个目录的NSArray
-
(BOOL)isAbsolutePath
是否为绝对路径
-
(NSString *)lastPathComponent
获得最后一个目录
-
(NSString *)stringByDeletingLastPathComponent
删除最后一个目录
-
(NSString *)stringByAppendingPathComponent:(NSString *)str
在路径的后面拼接一个目录
NSString与拓展名
-
(NSString *)pathExtension
获得拓展名
-
(NSString *)stringByDeletingPathExtension
删除尾部的拓展名
-
(NSString *)stringByAppendingPathExtension:(NSString *)str
在尾部添加一个拓展名
NSString其他用法
-
(NSUInteger)length
返回字符串的长度(字符个数)
-
(unichar)characterAtIndex:(NSUInteger)index
返回index位置对应的字符
-
(double)doubleValue
-
(float)floatValue
-
(int)intValue
-
(char *)UTF8String
转为C语言中的字符串
NSMutableString
NSString是不可变的,不能删除字符或者添加字符。NSString有一个子类NSMutableString,称为”可变字符串”
创建可变字符串的常用方法
(id)initWithCapacity:(NSUInteger)capacity
(id)stringWithCapacity:(NSUInteger)capacity
capacity只是一个最优值,字符串的大小并不仅限于所提供的容量,设置了capacity,可以预分配一块内存来存储它,操作速度会快很多
当然,也可以使用创建NSString的方法来创建NSMutableString,因为NSMutableString是NSString的子类,NSString能用的方法,NSMutableString都能使用
NSMutableString常用处理
-
(void)setString:(NSString *)aString
初始化完毕后可以使用此方法设置字符串的内容
-
(void)appendString:(NSString *)aString
-
(void)appendFormat:(NSString *)format, ...
这两个方法都是在尾部拼接一段字符串
-
(void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString
将range位置的字符串替换为aString
-
(void)insertString:(NSString *)aString atIndex:(NSUInteger)loc
在loc这个位置插入aString(aString的起始位置是就loc)
-
(void)deleteCharactersInRange:(NSRange)range
删除range这个范围的字符串(经常跟rangeOfString:一起使用删除特定的字符串)
NSArray
用来存储对象的有序列表,它是不可变的
不能直接存储C语言中的基本数据类型,如int、float、enum、struct,也不能存储nil
创建NSArray的常用方法
+
(id)array
+
(id)arrayWithObject:(id)anObject
+
(id)arrayWithObjects:(id)firstObj, ...
+
(id)arrayWithArray:(NSArray *)array
-
(id)initWithObjects:(id)firstObj, ...
-
(id)initWithArray:(NSArray *)array
+
(id)arrayWithContentsOfFile:(NSString *)path
+
(id)arrayWithContentsOfURL:(NSURL *)url
-
(id)initWithContentsOfFile:(NSString *)path
-
(id)initWithContentsOfURL:(NSURL *)url
NSArray查询
-
(NSUInteger)count
获取集合元素个数
-
(BOOL)containsObject:(id)anObject
是否包含某一个元素
-
(id)lastObject
返回最后一个元素
-
(id)objectAtIndex:(NSUInteger)index
获得index位置对象的元素
-
(NSUInteger)indexOfObject:(id)anObject
查找元素的位置
-
(NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range
在range范围内查找元素的位置
NSArray比较
-
(BOOL)isEqualToArray:(NSArray *)otherArray
比较两个集合内容是否相同
-
(id)firstObjectCommonWithArray:(NSArray *)otherArray
返回两个集合中第一个相同的对象元素
NSArray给元素发送消息
-
(void)makeObjectsPerformSelector:(SEL)aSelector
-
(void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument
让集合里面的所有元素都执行aSelector这个方法
NSArray遍历
普通遍历
NSUInteger
count = [array count];
for
(int i = 0; i < count; i++) {
id obj = [array objectAtIndex:i];
}
快速遍历
for
(id obj in
array)
迭代器遍历(查看NSEnumerator的用法)
block遍历
[array
enumerateObjectsUsingBlock:^(id
object, NSUInteger index, BOOL *stop) {
NSLog(@"%@ - %zi", object, index);
}]
NSEnumerator
集合的迭代器,可用于遍历集合元素
NSArray有相应的方法来可以获取迭代器
(NSEnumerator *)objectEnumerator
获取一个正序遍历的迭代器
(NSEnumerator *)reverseObjectEnumerator
获取一个反序遍历的迭代器
NSEnumerator常用方法
(id)nextObject
获取下一个元素
(NSArray *)allObjects
获取没有被遍历过的元素
NSArray派生出新的集合
-
(NSArray *)arrayByAddingObject:(id)anObject
添加一个元素,返回一个新的NSArray(方法调用者本身没有改变)
-
(NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray
添加otherArray的所有元素,返回一个新的NSArray(方法调用者本身没有改变)
-
(NSArray *)subarrayWithRange:(NSRange)range
截取range范围的数组元素
NSArray其他方法
-
(NSString *)componentsJoinedByString:(NSString *)separator
用separator作拼接符将数组元素拼接成一个字符串
-
(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
将一个NSArray持久化到文件中去
NSArray排序
-
(NSArray *)sortedArrayUsingSelector:(SEL)comparator
例如这样调用(假设array里面装着Student对象):
[array
sortedArrayUsingSelector:@selector(compare:)]
那么Student必须实现compare:这个方法,按照Student的_name属性来排序
-
(NSComparisonResult)compare:(Student *)stu {
return [_name
compare:stu.name];
}
-
(NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
//typedef
NSComparisonResult (^NSComparator)(id obj1, id obj2);
[array
sortedArrayUsingComparator:^(Student *s1, Student *s2) {
return [s1.name compare:s2.name];
}]; // 按照name排序
NSArray排序
-
(NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors
NSArray排序
NSSortDecriptor的初始化方法
(id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending
默认是用compare:作为比较方法
(id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending
selector:(SEL)selector
可以传递一个selector设置比较方法
(id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending
comparator:(NSComparator)cmptr
可以传递一个block来专门比较
NSArray的内存管理
每当有一个对象添加到NSArray中,都会对这个对象做一次retain操作
当NSArray被销毁时,会对内部存放的所有对象都做一次release操作
NSMutableArray
可变的NSArray,NSArray的子类,可以随意的添加或者删除元素
创建NSMutableArray的方法:
(id)arrayWithCapacity:(NSUInteger)numItems
(id)initWithCapacity:(NSUInteger)numItems
也可以使用创建NSArray的方法来创建NSMutableArray
当一个元素被加到集合中时,会执行一次retain操作;当一个元素从集合中移除时,会执行一次release操作;当集合被销毁时(调用了dealloc),集合里的所有元素都会执行一次release操作(这个原则还适用于其他集合:NSDictionary\NSSet等)
NSMutableArray添加元素
-
(void)setArray:(NSArray *)otherArray
设置集合元素
-
(void)addObject:(id)anObject
添加一个元素
-
(void)addObjectsFromArray:(NSArray *)otherArray
添加otherArray的全部元素到集合中
-
(void)insertObject:(id)anObject atIndex:(NSUInteger)index
在index位置插入一个元素
-
(void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
在indexes指定的位置分别插入objects中的元素
NSMutableArray删除元素
-
(void)removeLastObject
删除最后一个元素
-
(void)removeAllObjects
删除所有的元素
-
(void)removeObjectAtIndex:(NSUInteger)index
删除index位置的元素
-
(void)removeObjectsAtIndexes:(NSIndexSet *)indexes
删除indexes位置的所有元素
-
(void)removeObject:(id)anObject
删除特定的元素
-
(void)removeObject:(id)anObject inRange:(NSRange)range
在range范围内查找特定的元素进行删除
-
(void)removeObjectsInArray:(NSArray *)otherArray
删除同时存在于otherArray和当前集合中的所有元素
-
(void)removeObjectsInRange:(NSRange)range
删除range范围内的所有元素
NSMutableArray替换元素
-
(void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
用anObject替换index位置对应的元素
-
(void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray
*)objects
用objects中的元素分别替换indexes对应位置的元素
-
(void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray
*)otherArray range:(NSRange)otherRange
用otherArray中otherRange范围内的元素替换当前集合range范围内的元素
-
(void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray
*)otherArray
用otherArray中的元素替换当前集合range范围内的元素
-
(void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2
交换idx1和idx2位置的元素
NSMutableArray排序
-
(void)sortUsingDescriptors:(NSArray *)sortDescriptors
-
(void)sortUsingComparator:(NSComparator)cmptr
-
(void)sortUsingSelector:(SEL)comparator
用法参考NSArray的排序
NSMutableArray的内存管理
每当有一个元素添加到NSMutableArray中,都会对这个元素做一次retain操作
每当有一个对象从NSMutableArray中移除中,都会对这个元素做一次release操作
当NSMutableArray被销毁时,会对内部存放的所有元素做一次release操作
NSDictionary
通过唯一的key找到对应的value,类似于Java的Map
常见的创建NSDictionary的方法
+
(id)dictionary
+
(id)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key
+
(id)dictionaryWithObjectsAndKeys:(id)firstObject, ...
+
(id)dictionaryWithDictionary:(NSDictionary *)dict
+
(id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
-
(id)initWithObjectsAndKeys:(id)firstObject, ...
-
(id)initWithDictionary:(NSDictionary *)otherDictionary
-
(id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
+
(id)dictionaryWithContentsOfFile:(NSString *)path
+
(id)dictionaryWithContentsOfURL:(NSURL *)url
-
(id)initWithContentsOfFile:(NSString *)path
-
(id)initWithContentsOfURL:(NSURL *)url
NSDictionary常用方法
-
(NSUInteger)count
返回字典的key数
-
(BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary
比较两个字典
-
(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
将一个NSDicionary持久化到文件中去
NSDictionary访问key和value
-
(NSArray *)allKeys
返回所有的key
-
(NSArray *)allKeysForObject:(id)anObject
返回anObject元素对应的所有key
-
(NSArray *)allValues
返回所有的value
-
(id)objectForKey:(id)aKey
根据aKey返回对应的value
-
(NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)marker
返回keys对应的所有value,如果没有对应的value,用marker代替
NSDictionry遍历
快速遍历:for
(NSString *key in dict)
迭代器遍历:
(NSEnumerator *)keyEnumerator
key的迭代器
(NSEnumerator *)objectEnumerator
value的迭代器
block遍历
[dict
enumerateKeysAndObjectsUsingBlock:^(id
key,
id object, BOOL* stop) {
NSLog(@"key=%@, object=%@", key,
object);
}];
NSDictionary的key排序
-
(NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
-
(NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts
usingComparator:(NSComparator)cmptr
-
(NSArray *)keysSortedByValueUsingSelector:(SEL)comparator
用法参展NSArray的排序
NSMutableDictionary
可变的NSDictionary,NSDictionary的子类
初始化方法:
(id)dictionaryWithCapacity:(NSUInteger)numItems
(id)initWithCapacity:(NSUInteger)numItems
NSMutableDictionary添加元素
-
(void)setDictionary:(NSDictionary *)otherDictionary
设置当前集合的元素
-
(void)setObject:(id)anObject forKey:(id <NSCopying>)aKey
添加一个键值对
-
(void)addEntriesFromDictionary:(NSDictionary *)otherDictionary
添加otherDictionary的所有元素到当前集合中
NSMutableDictionary删除元素
-
(void)removeAllObjects
删除所有元素
-
(void)removeObjectForKey:(id)aKey
删除aKey对应的值
-
(void)removeObjectsForKeys:(NSArray *)keyArray
删除keyArray中所有key对应的值
NSNumber
NSNumber可以将基本数据类型包装成对象,这样就可以间接将基本数据类型存进NSArray、NSDictionary等集合中
常见的初始化方法:
+
(NSNumber *)numberWithChar:(char)value
+
(NSNumber *)numberWithInt:(int)value
+
(NSNumber *)numberWithFloat:(float)value
+
(NSNumber *)numberWithBool:(BOOL)value
-
(id)initWithChar:(char)value
-
(id)initWithInt:(int)value
-
(id)initWithFloat:(float)value
-
(id)initWithBool:(BOOL)value
NSNumber常用方法
-
(char)charValue
-
(int)intValue
-
(double)doubleValue
-
(BOOL)boolValue
-
(NSString *)stringValue
-
(NSComparisonResult)compare:(NSNumber *)otherNumber
-
(BOOL)isEqualToNumber:(NSNumber *)number
NSValue
NSNumber是NSValue的子类,但NSNumber只能包装数字类型,NSValue可以包装任意值.也就可以用NSValue包装结构体后加入NSArray、NSDictionary等集合中
创建NSValue的常用方法
(id)initWithBytes:(const void *)value objCType:(const char *)type
(NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type
(NSValue *)value:(const void *)value withObjCType:(const char *)type
value参数是想要包装的数据的地址(如一个NSPoint的地址,可以用&来取地址),type参数是用来描述这个数据类型的字符串,用@encode指令来生成
NSValue常用方法
-
(void)getValue:(void *)value
获取所包装的数据, 保存到value这个地址
-
(const char *)objCType
返回描述所包装数据类型的字符串
-
(BOOL)isEqualToValue:(NSValue *)value
NSValue常用方法
为了方便struct和NSValue的转换,cocoa还提供了以下方法
+
(NSValue *)valueWithPoint:(NSPoint)point
+
(NSValue *)valueWithSize:(NSSize)size
+
(NSValue *)valueWithRect:(NSRect)rect
-
(NSPoint)pointValue
-
(NSSize)sizeValue
-
(NSRect)rectValue
NSNull
集合中是不能存放nil值的,因为nil在集合中有特殊含义,但有时确实需要存储一个表示”什么都没有”的值,那么就可以使用NSNull,它也是NSObject的一个子类
创建和获取NSNull的方法
+
(NSNull *)null
[NSNull
null]总是返回一样的值,所以可以用==将该值与其他值进行比较
NSMutableDictionary
*dict = [NSMutableDictionary dictionary];
[dict
setValue:[NSNull null] forKey:@"work number"];
id
value = [dict valueForKey:@"work number"];
if
(value == [NSNull null]) {
NSLog(@"work number dosen't
exist.");
}
NSDate的静态初始化
+
(id)date
返回当前时间
+
(id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs
返回以当前时间为基准,然后过了secs秒的时间
+
(id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs
返回以2001/01/01 GMT为基准,然后过了secs秒的时间
+
(id)dateWithTimeIntervalSince1970:(NSTimeInterval)secs
返回以1970/01/01 GMT为基准,然后过了secs秒的时间
+
(id)distantFuture
返回很多年以后的未来的某一天
+
(id)distantPast
返回很多年以前的某一天
NSDate的动态初始化
-
(id)addTimeInterval:(NSTimeInterval)secs
返回以目前的实例中保存的时间为基准,然后过了secs秒的时间
-
(id)init
初始化为当前时间。[NSDate
date]
-
(id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs
初始化为以2001/01/01
GMT为基准,然后过了secs秒的时间
-
(id)initWithTimeInterval:(NSTimeInterval)secs sinceDate:(NSDate *)refDate
初始化为以refDate为基准,然后过了secs秒的时间
-
(id)initWithTimeIntervalSinceNow:(NSTimeInterval)secs
初始化为以当前时间为基准,然后过了secs秒的时间
NSDate日期比较
-
(BOOL)isEqualToDate:(NSDate *)otherDate
与otherDate比较,相同返回YES
-
(NSDate *)earlierDate:(NSDate *)anotherDate
与anotherDate比较,返回较早的那个日期
-
(NSDate *)laterDate:(NSDate *)anotherDate
与anotherDate比较,返回较晚的那个日期
-
(NSComparisonResult)compare:(NSDate *)other
该方法用于排序时调用:
. 当实例保存的日期值与anotherDate相同时返回NSOrderedSame
. 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending
. 当实例保存的日期值早于anotherDate时返回NSOrderedAscending
NSDate取回时间间隔
-
(NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate
以refDate为基准时间,返回实例保存的时间与refDate的时间间隔
-
(NSTimeInterval)timeIntervalSinceNow
以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔
-
(NSTimeInterval)timeIntervalSince1970
以1970/01/01
GMT为基准时间,返回实例保存的时间与1970/01/01
GMT的时间间隔
-
(NSTimeInterval)timeIntervalSinceReferenceDate
以2001/01/01
GMT为基准时间,返回实例保存的时间与2001/01/01
GMT的时间间隔
+
(NSTimeInterval)timeIntervalSinceReferenceDate
以2001/01/01
GMT为基准时间,返回当前时间(Now)与2001/01/01
GMT的时间间隔
NSDate日期格式化
NSDateFormatter *formatter =
[[[NSDateFormatter alloc] init] autorelease];
formatter.dateFormat =
@"yyyy-MM-dd HH:mm:ss";
// 将NSString转换为NSDate
NSDate *date = [formatter
dateFromString:@"2010-03-24 00:00:00"];
// 将NSDate转换为NSString
NSLog(@"%@", [formatter
stringFromDate:date]);
NSObject常用方法
-
(BOOL)isKindOfClass:(Class)aClass
判断是否为aClass或者aClass的子类的实例
-
(BOOL)isMemberOfClass:(Class)aClass
判断是否为aClass的实例(不包括aClass的子类)
-
(BOOL)conformsToProtocol:(Protocol)aProtocol
判断对象是否实现了aProtocol协议
+
(BOOL)instancesRespondToSelector:(SEL)aSelector
判断这个类的对象是否拥有参数提供的方法
-
(BOOL)respondsToSelector:(SEL)aSelector
判断对象是否拥有参数提供的方法
-
(void)performSelector:(SEL)aSelector withObject:(id)anArgument
afterDelay:(NSTimeInterval)delay
延迟调用参数提供的方法,方法所需参数用withObject传入
反射
Class的反射
Class
class = NSClassFromString(@"Student");
Student
*stu = [[class alloc] init];
Class
class = [Student class];
NSString
*className = NSStringFromClass(class);
SEL的反射
SEL
selector = NSSelectorFromString(@"setName:");
[stu
performSelector:selector withObject:@"Mike"];
NSStringFromSelector(@selector(setName:));
copy和mutableCopy
一个对象使用copy或mutableCopy方法可以创建对象的副本
copy – 需要先实现NSCoppying协议,创建的是不可变副本(如NSString、NSArray、NSDictionary)
mutableCopy – 需要先实现NSMutableCopying协议,创建的是可变副本(如NSMutableString、NSMutableArray、NSMutableDictionary)
深复制:内容拷贝,源对象和副本指向的是不同的两个对象。源对象引用计数器不变,副本计数器设置为1
浅复制:指针拷贝,源对象和副本指向的是同一个对象。对象的引用计数器+1,其实相当于做了一次retain操作
只有不可变对象创建不可变副本(copy)才是浅复制,其他都是深复制
常见复制
为自定义类添加复制功能
如果想自定义copy,那么就必须遵守NSCopying,并且实现
copyWithZone:方法
如果想自定义mutableCopy,那么就必须遵守NSMutableCopying,并且实现
mutableCopyWithZone:
方法
以copy为例,建议用[self
class]代替直接类名
-
(id)copyWithZone:(NSZone *)zone {
id copy = [[[self class]
allocWithZone:zone] init];
// 做一些属性的初始化.....
return copy;
}
深拷贝:内容拷贝
浅拷贝:指针拷贝
最新文章
- RFID-RC522、FM1702SL、M1卡初探
- Visual Studio通过Web Deploy发布网站报错:An error occurred when the request was processed on the remote computer.
- iOS中打印系统详细日志
- Structs
- linux复制文件命令scp
- 读书笔记 effective c++ Item 39 明智而谨慎的使用private继承
- 关于ng路由的传参问题(传递一个,多个参数)
- What is the difference between Debug and Release in Visual Studio?
- java开发3轮技术面+hr面 面经(MT)
- jQuery遮罩层插件
- (97)Wangdao.com_第三十天_触摸事件
- Docker最全教程——从理论到实战
- Centos6.8 搭建Nginx服务器
- layer弹窗和日期
- 算法笔记 #007# Backtracking
- 【SpringBoot】支持Java1.6
- Selenium + Python + Firefox
- Codeforces Round #265 (Div. 2) E. Substitutes in Number
- webserive学习记录3-eclipse创建webservice
- 你对position的了解有多少?