IOS工具类 (钱转化(分到元),快速创建控件,生成图片名称,验证信息,缓存文件,友盟统计类,转换为json,获取URl中的参数)

项目所用到的自定义工具总结

钱转化(分到元)

+ (NSString *)changeformatterWithFen:(id)money

{

    if ([money isKindOfClass:[NSString class]]) {

        return money;

    }else if([money isKindOfClass:[NSNumber class]]) {

        NSString *yuanString = nil;

        NSInteger moneyInt = ((NSNumber *)money).integerValue;

        if (moneyInt % 100 == 0) {

            yuanString = [NSString stringWithFormat:@"%d",moneyInt/100];

        }else if(moneyInt%100%10 == 0){

             yuanString = [NSString stringWithFormat:@"%.1f",moneyInt/100.0];

        }else{

            yuanString = [NSString stringWithFormat:@"%.2f",moneyInt/100.0];

        }

        return yuanString;

    }else{

        return @" ";

    }

}


+ (NSString *)formatterWithFen:(id)money

{

    if ([money isKindOfClass:[NSString class]]) {

        return money;

    }else if([money isKindOfClass:[NSNumber class]]) {

        NSString *yuanString = nil;

        NSInteger moneyInt = ((NSNumber *)money).integerValue;

        if (moneyInt % 100 == 0) {

            yuanString = [NSString stringWithFormat:@"%d",moneyInt/100];

        }else if(moneyInt%100%10 == 0){

            yuanString = [NSString stringWithFormat:@"%.1f",moneyInt/100.0];

        }else{

            yuanString = [NSString stringWithFormat:@"%.2f",moneyInt/100.0];

        }

        return yuanString;

    }else{

        return @" ";

    }

}

快速创建控件

/**

 *  得到UIView控件

 */

static inline UIView * createUIView(CGRect frame) {

    UIView * view = [[UIView alloc] initWithFrame:frame];

    return view;

}


/**

 *  得到UIButton控件

 */

static inline UIButton * createUIButton(CGRect frame,UIButtonType buttonType, id objc, SEL sel) {

    UIButton * btn = [UIButton buttonWithType:buttonType];

    btn.frame = frame;

    [btn addTarget:objc action:sel forControlEvents:UIControlEventTouchUpInside];

    return btn;

}


/**

 *  得到UIImageView控件

 */

static inline UIImageView * createUIImageView(CGRect frame) {

    UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];

    return imageView;

}


/**

 *  得到UILabel控件

 */

static inline UILabel * createUILabel(CGRect frame, NSString * text,UIFont * font) {

    UILabel * label = [[UILabel alloc] initWithFrame:frame];

    label.text = text;

    label.font = font;

    return label;

}

/**

 *  得到UITextField控件

 */

static inline UITextField * createUITextField(CGRect frame) {

    UITextField * textField = [[UITextField alloc] initWithFrame:frame];

    return textField;

}


/**

 *  得到UIScrollView控件

 */

static inline UIScrollView * createUIScrollView(CGRect frame, BOOL isBounces, BOOL isShowVerticalScrollIndicator, BOOL isShowHorizontalScrollIndicator) {

    UIScrollView * ScrollView = [[UIScrollView alloc] initWithFrame:frame];

    ScrollView.bounces = isBounces;

    ScrollView.showsHorizontalScrollIndicator = isShowHorizontalScrollIndicator;

    ScrollView.showsVerticalScrollIndicator = isShowVerticalScrollIndicator;

    return ScrollView;

}


/**

 *  得到UISegmentedControl控件, items@[@"标题1", @"标题2"]

 */

static inline UISegmentedControl * createUISegmentedControlWithItems(NSArray *items, CGRect frame , id object, SEL action)

{

    UISegmentedControl * segmentedControl = [[UISegmentedControl alloc] initWithItems:items];

    segmentedControl.frame = frame;

    [segmentedControl addTarget:object action:action forControlEvents:UIControlEventValueChanged];

    return segmentedControl;

}


/**

 * 返回属性字符串例如: 我是好人,假如把字变成特殊颜色的就这样

 * 字符串可是是空   @""  例如把 变成特殊字就 headerString @""  middleString @"" behindString @"是好人"

 *  @param headerString  我是

 *  @param middleString  

 *  @param behindString  

 *  @param puTongFont    前后字体的Font

 *  @param puTongColor   前后字体的颜色

 *  @param zhongJianFont 中间字体的font

 *  @param zhongJianColor中间字体的颜色

 *    UILabel * lab ;

 lab.attributedText = 在这里赋值label ;   lab.attributedText,不是用lab.text

 *  @return NSMutableAttributedString

 */

static inline NSMutableAttributedString * getAttributedString(NSString * headerString, NSString * middleString, NSString * behindString,UIFont * puTongFont, UIColor * puTongColor ,UIFont * zhongJianFont, UIColor * zhongJianColor)

{

    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@", headerString, middleString, behindString]];

    [attributedString beginEditing];

    [attributedString addAttribute:NSForegroundColorAttributeName value:puTongColor range:NSMakeRange(0, attributedString.length)];

    [attributedString addAttribute:NSFontAttributeName value:puTongFont range:NSMakeRange(0, attributedString.length)];

    [attributedString addAttribute:NSForegroundColorAttributeName value:zhongJianColor range:NSMakeRange(headerString.length, middleString.length)];

    [attributedString addAttribute:NSFontAttributeName value:zhongJianFont range:NSMakeRange(headerString.length, middleString.length)];

    [attributedString endEditing];

    return attributedString;

}

生成图片名称

- (NSString *)generateImgKeyWithUserID:(NSString *)userId imageName:(NSString *)imageName

{

    NSString *imageKey = nil;

    userId = userId?userId:@"";

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@"yyyyMMddHHmm"];

    NSString *dateStr = [formatter stringFromDate:[NSDate date]];

    DLog(@"分钟:%@",dateStr);


    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];

    NSString *millisecond =[formatter stringFromDate:[NSDate date]];

    DLog(@"毫秒:%@",millisecond);

    if (!imageName) {

        imageName = dateStr;

    }

    NSString *randomStr = [imageName stringByAppendingFormat:@"|%@|%@",millisecond,userId];

    randomStr = [randomStr md5HexDigest];

    imageKey = [dateStr stringByAppendingString:[randomStr substringWithRange:NSMakeRange(0,25)]];

    return imageKey;

}

验证信息

#pragma 正则匹配手机号

+ (BOOL)checkTelNumber:(NSString *) telNumber

{

    NSString *pattern = @"^1+[3|5|7|8]+\\d{9}$";

//    NSString *pattern = @"^((13[0-9])|(17[7,8,6])|(15[^4,\\D])|(18[0-9]))+\\d{8}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred evaluateWithObject:telNumber];

    return isMatch;

}


#pragma mark -正则匹配手机验证码

+ (BOOL)checkCodeNumber:(NSString *)codeNumber

{

     NSString *pattern = @"\\d{4,6}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred evaluateWithObject:codeNumber];

    return isMatch;

}


#pragma 正则匹配用户密码6-16

+ (BOOL)checkPassword:(NSString *) password

{

//    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";

    NSString *pattern = @"[\\s|\\S]{6,16}$"; //[\\s|\\S]所有字符

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred evaluateWithObject:password];

    return isMatch;

    

}


#pragma正则匹配用户姓名,2-16位的中文或英文或数字或_

+ (BOOL)checkUserName : (NSString *) userName

{

    NSString *pattern = @"^([\u4e00-\u9fa5A-Za-z0-9_]+){2,16}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred evaluateWithObject:userName];

    return isMatch;

    

}



#pragma 正则匹配用户身份证号1518

+ (BOOL)checkUserIdCard: (NSString *) idCard

{

    idCard = [idCard stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    

    NSInteger  length =0;

    if (!idCard) {

        return NO;

    }else {

        length = idCard.length;

        if (length !=15 && length !=18) {

            return NO;

        }

    }

    // 省份代码

    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];

    

    NSString *valueStart2 = [idCard substringToIndex:2];

    BOOL areaFlag =NO;

    for (NSString *areaCode in areasArray) {

        if ([areaCode isEqualToString:valueStart2]) {

            areaFlag =YES;

            break;

        }

    }

    

    if (!areaFlag) {

        return NO;

    }

    

    NSRegularExpression *regularExpression;

    NSUInteger numberofMatch;

    

    NSInteger  year =0;

    if (length == 15){

        year = [idCard substringWithRange:NSMakeRange(6,2)].intValue +1900;

        if ((year %4 ==0) || (year %100 ==0 && year %4 ==0)) {

            regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性

        }else {

            regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性

        }

        numberofMatch = [regularExpression numberOfMatchesInString:idCard options:NSMatchingReportProgress range:NSMakeRange(0, idCard.length)];

        

        if(numberofMatch >0) {

            return YES;

        }else {

            return NO;

        }

        

    }else if(length ==18){

        year = [[idCard substringWithRange:NSMakeRange(6,4)] intValue];

        if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {

            regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"

                                                                    options:NSRegularExpressionCaseInsensitive

                                                                      error:nil];//测试出生日期的合法性

        }else {

            regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"

                                                                    options:NSRegularExpressionCaseInsensitive

                                                                      error:nil];//测试出生日期的合法性

        }

        numberofMatch = [regularExpression numberOfMatchesInString:idCard options:NSMatchingReportProgress range:NSMakeRange(0, idCard.length)];

        if(numberofMatch >0) {

            NSInteger S = ([idCard substringWithRange:NSMakeRange(0,1)].intValue + [idCard substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([idCard substringWithRange:NSMakeRange(1,1)].intValue + [idCard substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([idCard substringWithRange:NSMakeRange(2,1)].intValue + [idCard substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([idCard substringWithRange:NSMakeRange(3,1)].intValue + [idCard substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([idCard substringWithRange:NSMakeRange(4,1)].intValue + [idCard substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([idCard substringWithRange:NSMakeRange(5,1)].intValue + [idCard substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([idCard substringWithRange:NSMakeRange(6,1)].intValue + [idCard substringWithRange:NSMakeRange(16,1)].intValue) *2 + [idCard substringWithRange:NSMakeRange(7,1)].intValue *1 + [idCard substringWithRange:NSMakeRange(8,1)].intValue *6 + [idCard substringWithRange:NSMakeRange(9,1)].intValue *3;

            NSInteger Y = S %11;

            NSString *M =@"F";

            NSString *JYM =@"10X98765432";

            M = [JYM substringWithRange:NSMakeRange(Y,1)];//判断校验位

            if ([M isEqualToString:[idCard substringWithRange:NSMakeRange(17,1)]]) {

                return YES;//检测ID的校验位

            }else {

                return YES;

            }

            

        }else {

            return NO;

        }

    }else{

        return  NO;

    }

}


#pragma 正则匹员工号,12位的数字

+ (BOOL)checkEmployeeNumber : (NSString *) number

{

    NSString *pattern = @"^[0-9]{12}$4";

    

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];

    BOOL isMatch = [pred evaluateWithObject:number];

    return isMatch;

    

}


缓存文件

#import "NDCacheFileManger.h"


@interface NDCacheFileManger ()

@property (nonatomic, strong) NSString *cachePath;

@end


@implementation NDCacheFileManger

@synthesize userPath = _userPath;


+ (NDCacheFileManger *) shareCache

{

    static NDCacheFileManger *shareInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        shareInstance = [[self alloc] init];

        shareInstance.cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

    });

    return shareInstance;

}


- (void)setUserPath:(NSString *)userPath

{

    _userPath = userPath;

    [[NSUserDefaults standardUserDefaults] setObject:userPath forKey:kUserCachePath];

    [[NSUserDefaults standardUserDefaults] synchronize];

    

}

- (NSString *)userPath

{

     return [[NSUserDefaults standardUserDefaults] objectForKey:kUserCachePath];

}


//创建缓存文件夹

 -(BOOL) createDirInCache:(NSString *)dirName

 {

    NSString *imageDir =  [self.cachePath stringByAppendingPathComponent:dirName];

    BOOL isDir = NO;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL existed = [fileManager fileExistsAtPath:imageDir isDirectory:&isDir];

    BOOL isCreated = NO;

    if (!(isDir == YES && existed == YES))

    {

        isCreated = [fileManager createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];

        self.userPath = imageDir;

    }

    if (existed) {

        isCreated = YES;

    }

     DLog(@"userPaht = %@",self.userPath);

     return isCreated;

}


-(BOOL) saveToFile:(NSString *)file inDirectory:(NSString *)directoryPath data:(NSDictionary *)dataObject

{

    BOOL isSaved = NO;

    BOOL isDir = NO;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (directoryPath.length == 0) {

        directoryPath = kCustomerID;

    }

    NSString *userDirectory = [self.cachePath stringByAppendingPathComponent:directoryPath];

    BOOL existed = [fileManager fileExistsAtPath:userDirectory isDirectory:&isDir];

    if (isDir && existed) {

        NSString *filePath = [userDirectory stringByAppendingPathComponent:file];

        isSaved = [dataObject writeToFile:filePath atomically:YES];

        DLog(@"filePath = %@",filePath);

    }

    return isSaved;

}


- (NSDictionary *) readFromFile:(NSString *)file inDirectory:(NSString *)directoryPath

{

    BOOL isDir = NO;

    

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (directoryPath.length == 0) {

        directoryPath = kCustomerID;

    }

    

    NSString *userDirectory = [self.cachePath stringByAppendingPathComponent:directoryPath];

    BOOL existed = [fileManager fileExistsAtPath:userDirectory isDirectory:&isDir];

    if (isDir && existed) {

        NSString *filePath = [userDirectory stringByAppendingPathComponent:file];

        existed = [fileManager fileExistsAtPath:filePath];

        if (existed) {

            NSDictionary *array = [NSDictionary dictionaryWithContentsOfFile:filePath];

            return array;

        }else{

            return nil;

        }

    }else

    {

        return nil;

    }

}

@end


友盟统计类

#import "MobClick.h"

#import "NDUMAnalyticsHelper.h"


@implementation NDUMAnalyticsHelper

+ (void)UMAnalyticStart {

    [MobClick startWithAppkey:UMeng_APIKey reportPolicy:BATCH channelId:@"App Store"];

    

    // version标识

    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    [MobClick setAppVersion:version];

    

#if DEBUG

   // 打开友盟sdk调试,注意Release发布时需要注释掉此行,减少io消耗

    [MobClick setLogEnabled:YES];

#endif

    return;

}


+ (void)beginLogPageView:(__unsafe_unretained Class)pageView {

    [MobClick beginLogPageView:NSStringFromClass(pageView)];

    return;

}


+ (void)endLogPageView:(__unsafe_unretained Class)pageView {

    [MobClick endLogPageView:NSStringFromClass(pageView)];

    return;

}


@end

获取URl中的参数

#import "NDUrlChangeTool.h"


@implementation NDUrlChangeTool

+(NSMutableDictionary *)dicFromUrl:(NSString *)urlStr

{

    

    NSRange range = [urlStr rangeOfString:@"?"];

    

    NSLog(@"参数列表开始的位置:%d", (int)range.location);

    

    //获取参数列表

    NSString *propertys = [urlStr substringFromIndex:(int)(range.location+1)];

    NSLog(@"截取的参数列表:%@", propertys);

    

   //进行字符串的拆分,通过&来拆分,把每个参数分开

    NSArray *subArray = [propertys componentsSeparatedByString:@"&"];

    NSLog(@"把每个参数列表进行拆分,返回为数组:\n%@", subArray);

    

    //subArray转换为字典

    //tempDic中存放一个URL中转换的键值对

    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithCapacity:4];

    

    for (int j = 0 ; j < subArray.count; j++)

    {

        //在通过=拆分键和值

        NSArray *dicArray = [subArray[j] componentsSeparatedByString:@"="];

        NSLog(@"再把每个参数通过=号进行拆分:\n%@", dicArray);

        //给字典加入元素

        [tempDic setObject:dicArray[1] forKey:dicArray[0]];

    }

    NSLog(@"打印参数列表生成的字典:\n%@", tempDic);

    return tempDic;

}

@end

@implementation NDStrTransJson


#pragma mark - 向服务器传递数组,转换为json格式

+(NSString *)transformArr:(NSMutableArray *)arr

{

#pragma mark - 删除

    NSString *jsonString = [[NSString alloc]init];

    NSError *error = nil;

    NSData *jsonData = [NSJSONSerialization

                        dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];

    if ([jsonData length] > 0 && error == nil){

        //NSData转换为String

        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    else if ([jsonData length] == 0 &&

             error == nil){

    }

    else if (error != nil){

    }

    return jsonString;

}



@end






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值