结构体
NSRange:
用来表示范围
创建
NSRange r1 = {2, 4}
NSRange r2 = {.location = 2, .length = 4}
NSRange r3 = NSMakeRange(2, 4)
查找某个字符串在str中的范围
NSString *str = @"i love oc";
NSRange range = [str rangeOfString:@"java"]
NSLog(@"location = %ld, length=%ld", range.location, range.length)
如果找不到,length=0,location=NSNotFound==-1
NSPoint:
用来表示一个点的坐标
创建
CGPoint p1 = NSMakePoint(10, 10);
NSPoint p2 = CGPointMake(20, 20);
表示原点
CGPointZero == CGPointMake(0, 0)
NSSize:
表示二维平面的尺寸
NSSize s1 = CGSizeMake(100, 50);
NSSize s2 = NSMakeSize(100, 50);
CGSize s3 = NSMakeSize(200, 60);
CGRect:
表示二维平面具体的一个尺寸和位置
CGRect r1 = CGRectMake(0, 0, 100, 50);
CGRect r2 = { {0, 0}, {100, 90}};
CGRect r3 = {p1, s2};
定义CGRect的另外方法
CGRect myRect(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x;
rect.origin.y = y;
rect.size.width = width;
rect.size.height = height;
}
将结构体转为字符串
NSString *str = NSStringFromPoint(p1);
NSString *str = NSStringFromSize(s3);
NSString *str = NSStringFromRect(r1);
比较两个点是否相同(x、y)
BOOL b = CGPointEqualToPoint(CGPointMake(10, 10), CGPointMake(10, 10))
判断一个点是否在某个区域
BOOL b2 = CGRectContainsPoint(CGRectMake(50, 40, 100, 50), CGPointMake(60, 45))
使用这些CGPointEqualToPoint、CGRectContainsPoint等函数的前提是添加CoreGraphics框架
NSString
字符串的创建
NSString *s1 = @"jack";
NSString *s2 = [[NSString alloc] initWithString:@"jack"];
NSString *s3 = [[NSString alloc] initWithFormat:@"age is %d", 10];
C字符串 > C字符串
const char *c = [s4 UTF8String];
NSUTF8StringEncoding 用到中文就可以用这种编码
NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];
字符串的导出
NSString *str = @"4234234";
NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/my2.txt"];
[str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
或者
[@"Jack\nJack" writeToFile:@"/Users/apple/Desktop/my.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]
NSMutableString
可变字符串
NSMutableString *s1 = [NSMutableString stringWithFormat:@"my age is 10"];
拼接内容到s1的后面
[s1 appendString:@" 11 12"];
获取is的范围
NSRange range = [s1 rangeOfString:@"is"];
删除is
[s1 deleteCharactersInRange:range];
不可变字符串也可以将两个字符串拼接
NSString *s2 = [NSString stringWithFormat:@"age is 10"];
NSString *s3 = [s2 stringByAppendingString:@" 11 12"];
补充知识:NSURL
file:// 本地资源协议头
http:// 网络资源协议头
创建一个资源路径
NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/1.txt"] 本地资源
NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/1.txt"] 本地资源
将资源路径转化为字符串
NSString *s6 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]