logo头像

小玉的技术博客

OC常用方法总结

以下方法是本人在实际学习及开发中总结出来备忘,分享给大家

JSON格式的字符串转换成字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 把格式化的JSON格式的字符串转换成字典
* @param jsonString JSON格式的字符串
* @return 返回字典
*/
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if(err) return nil;
return dic;
}

字典转json格式字符串

1
2
3
4
5
6
7
8
9
/**
* 字典转json格式字符串
* @return Json字符串
*/
- (NSString*)dictionaryToJson {
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

加载本地json文件

1
2
3
4
5
6
//获取文件路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"JsonFileName" ofType:@"json"];
//根据文件路径读取数据
NSData *jdata = [[NSData alloc]initWithContentsOfFile:filePath];
//格式化成json数据
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jdata options:kNilOptions error:&error];

判断字符串是否是纯数字

1
2
3
4
5
6
7
8
9
10
/**
判断字符串是否是纯数字
@param string 带判断字符串
@return 是/否
*/
- (BOOL)isNumber:(NSString *)string {
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return [scan scanInt:&val] && [scan isAtEnd];
}

根据正则,过滤特殊字符

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 根据正则,过滤特殊字符
* @param regexString 正则表达式
* @return 过滤后的字符串
*/
- (NSString *)filterCharactorWithRegex:(NSString *)regexString {
NSString *searchText = self;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
return result;
}

邮箱验证

1
2
3
4
5
6
7
8
9
10
11
/**
* 邮箱验证
* @param email 邮箱地址
* @return 是否
*/
+ (BOOL)isValidateEmail:(NSString *)email {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}

手机号码验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 手机号码验证
*
* @param mobileNum 手机号
*
* @return 是否
*/
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
if (mobileNum.length != 11){
return NO;
}
/**
* 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
* 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
* 联通号段: 130,131,132,145,152,155,156,170,171,176,185,186
* 电信号段: 133,134,153,170,173,177,180,181,189
*/
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[013678]|8[0-9])\\d{8}$";
/**
* 中国移动:China Mobile
* 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
*/
NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
/**
* 中国联通:China Unicom
* 130,131,132,145,152,155,156,170,171,176,185,186
*/
NSString *CU = @"^1(3[0-2]|4[5]|5[256]|7[016]|8[56])\\d{8}$";
/**
* 中国电信:China Telecom
* 133,134,153,170,173,177,180,181,189
*/
NSString *CT = @"^1(3[34]|53|7[037]|8[019])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
if (([regextestmobile evaluateWithObject:mobileNum] == YES)
|| ([regextestcm evaluateWithObject:mobileNum] == YES)
|| ([regextestct evaluateWithObject:mobileNum] == YES)
|| ([regextestcu evaluateWithObject:mobileNum] == YES)){
return YES;
}
else{
return NO;
}
}

压缩图片成二进制数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 将图片压缩成二进制数据
* @param 图片
**/
+ (NSData *)compressImage:(UIImage *)image {
NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
if (imageData.length <= 1000*1000) {
return imageData;
} else if (imageData.length > 1000*1000 && imageData.length < 3000 * 1000) {
imageData = UIImageJPEGRepresentation(image, 0.8f);
return imageData;
} else if (imageData.length > 3000*1000 && imageData.length < 5000 * 1000) {
imageData = UIImageJPEGRepresentation(image, 0.6f);
return imageData;
} else {
imageData = UIImageJPEGRepresentation(image, 0.4f);
return imageData;
}
}

文字生成二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
生成二维码
@param codeString 二维码客串
@return 二维码图片
*/
+ (UIImage *)createQRCodeWithString:(NSString *)codeString{
// 1.创建过滤器
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢复默认
[filter setDefaults];
// 3.给过滤器添加数据(正则表达式/账号和密码)
NSString *dataString = codeString;
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKeyPath:@"inputMessage"];
// 4.获取输出的二维码
CIImage *outputImage = [filter outputImage];
// 5.将CIImage转换成UIImage,并放大显示
return [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:400];
}
/**
根据CIImage生成指定大小的UIImage
@param image CIImage
@param size 图片宽度
*/
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 1.创建bitmap;
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}

图片增加水印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 图片增加水印
*
* @param superImage 需要增加水印的图片
* @param subImage 水印图片
* @param posRect 水印的位置 和 水印的大小
*
* @return 加水印后的新图片
*/
- (UIImage *)addImageToSuperImage:(UIImage *)superImage withSubImage:(UIImage *)subImage andSubImagePosition:(CGRect)posRect{
UIGraphicsBeginImageContext(superImage.size);
[superImage drawInRect:CGRectMake(0, 0, superImage.size.width, superImage.size.height)];
//四个参数为水印图片的位置
[subImage drawInRect:posRect];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}

image添加倒影效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (void)setImageShadow {
CGRect frame = self.frame;
frame.origin.y += (frame.size.height + 1);
UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame];
self.clipsToBounds = TRUE;
reflectionImageView.contentMode = self.contentMode;
[reflectionImageView setImage:self.image];
reflectionImageView.transform = CGAffineTransformMakeScale(1.0, -1.0);
CALayer *reflectionLayer = [reflectionImageView layer];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.bounds = reflectionLayer.bounds;
gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2, reflectionLayer.bounds.size.height * 0.5);
gradientLayer.colors = [NSArray arrayWithObjects:
(id)[[UIColor clearColor] CGColor],
(id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil];
gradientLayer.startPoint = CGPointMake(0.5,0.5);
gradientLayer.endPoint = CGPointMake(0.5,1.0);
reflectionLayer.mask = gradientLayer;
[self.superview addSubview:reflectionImageView];
}

UIView背景颜色渐变

1
2
3
4
5
6
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];

获取app缓存大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 获取app缓存大小
**/
- (CGFloat)getCachSize {
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
// 获取自定义缓存大小
// 用枚举器遍历 一个文件夹的内容
// 1.获取 文件夹枚举器
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
__block NSUInteger count = 0;
// 2.遍历
for (NSString *fileName in enumerator) {
NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
//自定义所有缓存大小
count += fileDict.fileSize;
}
// 得到是字节 转化为M
CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
return totalSize;
}

跳进app权限设置

1
2
3
4
if (UIApplicationOpenSettingsURLString != NULL) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}

删除NSUserDefaults所有记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults {
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
}
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

统一收起键盘

1
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

修改textField的placeholder的字体颜色、大小

1
2
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

数组去重

1
2
3
NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];
@distinctUnionOfObjects.self 表示比较对象
@distinctUnionOfObjects.[key] 表示比较对象的任意keyboarded
支付宝打赏 微信打赏

赞赏是不耍流氓的鼓励