ios switch 传参

2015-09-09 11:14:02 weichuang_1 阅读数 8156

实际上,object-c中switch的参数只能是int,byte,char,short的类型。那么我们如何使用字符串作为参数呢?

一.字符串为数字字符串:如"1"、"2"
现将数字字符串转化为 数字类型:

NSString *tempA = @"123";
NSString *tempB = @"456";

1,字符串拼接
NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];

2,字符转int
int intString = [newString intValue];

3int转字符
NSString *stringInt = [NSString stringWithFormat:@"%d",intString];

4,字符转float
float floatString = [newString floatValue];

5float转字符
NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];

二.字符串不是数字字符串:

//把用到的字符串参数放到一个数组里
NSArray *aName = [NSArray arrayWithObjects:@"lee",@"tom",@"vivid",@"liming",@"stormer",@"jun",nil];

//比如我们要把@"stormer"作为switch的参数,则取到它在数组中的下标,然后在switch中根据下标来进行处理。
int index = [aName  indexOfObject:@"stormer"];
switch(index)
{
case 0: //xxxxx; break;
case 1: //xxxxx; break;
case 2: //xxxxx; break;
case 3: //xxxxx; break;
case 4: //这里就是stormer的代码处理部分; break;
case 5: //xxxxx; break;
....
}
2015-07-06 14:30:00 woshidaniu 阅读数 1185

//

//  ViewController.m

//  070703

//

//  Created by tianshangrenjian on 15/7/6.

//  Copyright © 2015 tianshangrenjian. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()<NSStreamDelegate>

- (IBAction)btStart:(id)sender;

@property (weak, nonatomic) IBOutlet UIButton *btSend;


@property (strong, nonatomic) NSInputStream *inputStream;

@property (strong, nonatomic) NSOutputStream *outputStream;



- (IBAction)btSendMsg:(id)sender;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (IBAction)btStart:(id)sender {

    CFReadStreamRef inputStream;

    CFWriteStreamRef outputStream;

    

    NSString *host=@"127.0.0.1";

    int nPort=12345;

    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, nPort, &inputStream, &outputStream);

    

    self.inputStream=(__bridge NSInputStream *)(inputStream);

    self.outputStream=(__bridge NSOutputStream *)(outputStream);

    self.inputStream.delegate=self;

    

    [self.inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    

    [self.inputStream open];

    [self.outputStream open];

    

    

    

}

- (void)readData

{

    uint8_t buffer[1024];

    NSInteger nLen=[self.inputStream read:buffer maxLength:1024];

    NSData *data=[NSData dataWithBytes:buffer length:nLen];

    NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"readData:%@",str);

}


- (void)stream:(nonnull NSStream *)aStream handleEvent:(NSStreamEvent)eventCode

{

    switch (eventCode) {

        case NSStreamEventHasBytesAvailable:

            [self readData];

            break;

            

        default:

            break;

    }

}

- (IBAction)btSendMsg:(id)sender {

    NSString *str=@"SCH:daniutest";

    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

    [self.outputStream write:data.bytes maxLength:data.length];

}

@end


2018-10-12 16:34:37 robinson_911 阅读数 1147

weex相关原理,请看官方网站

此IOS Weex demo实现的功能,从原生界面跳转到Weex容器页面,然后点击Weex容器页面的button(js)跳转到另一个原生界面。

一. 先上效果图

 

二.实现

1. weex容器渲染的js代码如下,上面第二张图的代码

启动一个本地的Node环境,可以通过浏览器访问,也可以通过Weex容器渲染成上面的第二张图的界面

import { createElement, Component } from 'rax';
import View from 'rax-view';
import Text from 'rax-text';
import Button from 'rax-button';

import { setTitle, openUrl, getAppStoken } from 'lib/jsbridge';
import styles from './app.css';

class APP extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timesPressed1: 0,
      list: [],
    };
  }
  componentDidMount() {
    // alert('请求错误'); // eslint-disable-line
  }

  handlePress = () => {
    this.setState({
      timesPressed1: this.state.timesPressed1 + 1,
    });
   // alert('弹框测试!!!'); // eslint-disable-line

    openUrl({
      // url: 'weex://go/scan',
      url: 'weex://go/ljDetail?orderId=123',
    });
  };

  render() {
    return (
      <View style={styles.body}>
        <Text style={styles.loadingText}>当前页面是个weex容器</Text>
        <Text style={styles.loadingText}>加载的是个weex页面</Text>
        <Button style={styles.button} onPress={this.handlePress}>点击我从weex页面跳转到原生</Button>
      </View>
    );
  }
}

export default APP;

2. 原生的Weex容器

NSString *url = @"http://10.50.62.53:9999/wxTest/index.html?lj_weexurl=http://10.50.62.53:9999/wxTest/index.js";

此容器的设计,当Weex加载失败的时候,可以将当前的展示成html页面,加载的是wxTest/index.html页面,不影响使用。

当Weex加载成功的时候,渲染的是wxTest/index.js的代码

#import "WXViewController.h"
#import <WeexSDK/WXSDKInstance.h>
#import <WeexSDK/WXSDKEngine.h>
#import <WeexSDK/WXUtility.h>
#import <WeexSDK/WXDebugTool.h>
#import <WeexSDK/WXSDKManager.h>
#import "UIViewController+WXDemoNaviBar.h"
#import "WXPrerenderManager.h"
#import "WXMonitor.h"
#import "WXTracingManager.h"

#import "LJWKWebView.h"
#import "LJWKWebViewUtils.h"

#define kNavAndStatuesHeight  64
#define kUseWeexFlag @"lj_weexurl"

@interface WXViewController ()

@property (nonatomic, strong) WXSDKInstance *instance;
@property (nonatomic, strong) UIView *weexView;
@property (nonatomic, assign) BOOL isUseWeexRender; //是否使用weex渲染
@property (nonatomic, strong) LJWKWebView *webView;

@end

@implementation WXViewController

#pragma mark -- dealloc
- (void)dealloc
{
    [_instance destroyInstance];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSAssert(NO, @"请使用initWithUrl初始化");
    }
    return self;
}

- (instancetype)initWithUrl:(NSURL *)url useWeexEnv:(BOOL)useWeexEnv
{
    self = [super init];
    if (self) {
        _url = url;
        _isUseWeexRender = useWeexEnv && ([url.absoluteString rangeOfString:kUseWeexFlag].location != NSNotFound);
    }
    return self;
}

#pragma mark -- life cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    [self setTopNavBarTitle:@"Weex Container"];
    [self setGrayTopBarBg];
    
    if (_isUseWeexRender) {
        [self.view setClipsToBounds:YES];
        [self renderWeex];
    }else{
        [self setDeafaultTopBarBg];
        [self setTopNavBackButton];
        [self setTopNavBarTitle:@"加载中..."];
        [self loadWebViewWithUrl:self.url.absoluteString];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_isUseWeexRender) {
        [self updateInstanceState:WeexInstanceAppear];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (_isUseWeexRender) {
        [self updateInstanceState:WeexInstanceDisappear];
    }
}

appdelegate代码

#import "AppDelegate.h"
#import "WXViewController.h"
#import "UIViewController+WXDemoNaviBar.h"
#import "WXLJCustomeEventModule.h"
#import "WXImgLoaderDefaultImpl.h"
#import "WXScannerVC.h"
#import "UIView+UIThreadCheck.h"
#import <WeexSDK/WeexSDK.h>
#import <AVFoundation/AVFoundation.h>
#import <ATSDK/ATManager.h>
#import "WXNavigationHandlerImpl.h"

#import "ViewController.h"
//#import "WXAnalyzerCenter.h"


#ifdef DEBUG
#import "DebugAnalyzer.h"
#endif

@interface AppDelegate ()
@end

@implementation AppDelegate

#pragma mark
#pragma mark application

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self initWeexSDK];
    
    ViewController *vc = [[ViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    [self startSplashScreen];
    
#if DEBUG
    // check if there are any UI changes on main thread.
    [UIView wx_checkUIThread];
#endif
    
    return YES;
}

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    if ([shortcutItem.type isEqualToString:QRSCAN]) {
        WXScannerVC * scanViewController = [[WXScannerVC alloc] init];
        [(WXRootViewController*)self.window.rootViewController pushViewController:scanViewController animated:YES];
    }
    if ([shortcutItem.type isEqualToString:QRSCAN_HISTORY]) {
//        WXScannerHistoryVC *scannerHistoryVC = [WXScannerHistoryVC new];
//        [(WXRootViewController*)self.window.rootViewController pushViewController:scannerHistoryVC animated:YES];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
#ifdef UITEST
#if !TARGET_IPHONE_SIMULATOR
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    setenv("GCOV_PREFIX", [documentsDirectory cStringUsingEncoding:NSUTF8StringEncoding], 1);
    setenv("GCOV_PREFIX_STRIP", "6", 1);
#endif
    extern void __gcov_flush(void);
    __gcov_flush();
#endif
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSString *newUrlStr = url.absoluteString;
    if([url.scheme isEqualToString:@"wxpage"]) {
        newUrlStr = [newUrlStr stringByReplacingOccurrencesOfString:@"wxpage://" withString:@"http://"];
    }
    UIViewController * viewController = [self demoController:newUrlStr];
//    ((WXViewController*)viewController).url = [NSURL URLWithString:newUrlStr];
    [(WXRootViewController*)self.window.rootViewController pushViewController:viewController animated:YES];
    return YES;
}

#pragma mark weex
- (void)initWeexSDK
{
    [WXAppConfiguration setAppGroup:@"AliApp"];
    [WXAppConfiguration setAppName:@"WeexDemo"];
    [WXAppConfiguration setExternalUserAgent:@"ExternalUA"];
    
    [WXSDKEngine initSDKEnvironment];
    
    [WXSDKEngine registerHandler:[WXImgLoaderDefaultImpl new] withProtocol:@protocol(WXImgLoaderProtocol)];
    [WXSDKEngine registerHandler:[WXNavigationHandlerImpl new] withProtocol:@protocol(WXNavigationProtocol)];
    
    // 注册自定义的JS回调原生方法的事件方法
    [WXSDKEngine registerHandler:[WXLJCustomeEventModule new] withProtocol:@protocol(WXModuleProtocol)];
    [WXSDKEngine registerModule:@"actionBridge" withClass:[WXLJCustomeEventModule class]];
    // 注册自定义的JS回调原生方法的事件方法
    
#ifdef DEBUG
    [WXAnalyzerCenter addWxAnalyzer:[DebugAnalyzer new]];
#endif
    
#if !(TARGET_IPHONE_SIMULATOR)
    [self checkUpdate];
#endif
    
#ifdef DEBUG
    [self atAddPlugin];
    [WXDebugTool setDebug:YES];
    [WXLog setLogLevel:WXLogLevelLog];
    
#ifndef UITEST
    [[ATManager shareInstance] show];
#endif
#else
    [WXDebugTool setDebug:NO];
    [WXLog setLogLevel:WXLogLevelError];
#endif
}

- (UIViewController *)demoController:(NSString*)url
{
//    NSString *url = @"http://10.50.62.53:9999/wxTest/index.js";
    //    NSString *url = @"http://10.50.62.53:9999/wxTableview/index.js";
    //    NSString *url = @"https://www.baidu.com/";
    UIViewController *demo = [[WXViewController alloc] initWithUrl:[NSURL URLWithString:url] useWeexEnv:YES];
    return demo;
}

#pragma mark
#pragma mark animation when startup

- (void)startSplashScreen
{
    UIView* splashView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    splashView.backgroundColor = WEEX_COLOR;
    
    UIImageView *iconImageView = [UIImageView new];
    UIImage *icon = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"weex-icon" ofType:@"png"]];
    if ([icon respondsToSelector:@selector(imageWithRenderingMode:)]) {
        iconImageView.image = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        iconImageView.tintColor = [UIColor whiteColor];
    } else {
        iconImageView.image = icon;
    }
    iconImageView.frame = CGRectMake(0, 0, 320, 320);
    iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    iconImageView.center = splashView.center;
    [splashView addSubview:iconImageView];
    
    [self.window addSubview:splashView];
    
    float animationDuration = 1.4;
    CGFloat shrinkDuration = animationDuration * 0.3;
    CGFloat growDuration = animationDuration * 0.7;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        [UIView animateWithDuration:shrinkDuration delay:1.0 usingSpringWithDamping:0.7f initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.75, 0.75);
            iconImageView.transform = scaleTransform;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:growDuration animations:^{
                CGAffineTransform scaleTransform = CGAffineTransformMakeScale(20, 20);
                iconImageView.transform = scaleTransform;
                splashView.alpha = 0;
            } completion:^(BOOL finished) {
                [splashView removeFromSuperview];
            }];
        }];
    } else {
        [UIView animateWithDuration:shrinkDuration delay:1.0 options:0 animations:^{
            CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.75, 0.75);
            iconImageView.transform = scaleTransform;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:growDuration animations:^{
                CGAffineTransform scaleTransform = CGAffineTransformMakeScale(20, 20);
                iconImageView.transform = scaleTransform;
                splashView.alpha = 0;
            } completion:^(BOOL finished) {
                [splashView removeFromSuperview];
            }];
        }];
    }
}

#pragma mark

- (void)atAddPlugin {
#if DEBUG
    [[ATManager shareInstance] addPluginWithId:@"weex" andName:@"weex" andIconName:@"../weex" andEntry:@"" andArgs:@[@""]];
    [[ATManager shareInstance] addSubPluginWithParentId:@"weex" andSubId:@"logger" andName:@"logger" andIconName:@"log" andEntry:@"WXATLoggerPlugin" andArgs:@[@""]];
    //    [[ATManager shareInstance] addSubPluginWithParentId:@"weex" andSubId:@"viewHierarchy" andName:@"hierarchy" andIconName:@"log" andEntry:@"WXATViewHierarchyPlugin" andArgs:@[@""]];
    [[ATManager shareInstance] addSubPluginWithParentId:@"weex" andSubId:@"test2" andName:@"test" andIconName:@"at_arr_refresh" andEntry:@"" andArgs:@[]];
    [[ATManager shareInstance] addSubPluginWithParentId:@"weex" andSubId:@"test3" andName:@"test" andIconName:@"at_arr_refresh" andEntry:@"" andArgs:@[]];
#endif
}

- (void)checkUpdate {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
        NSString *URL = @"http://itunes.apple.com/lookup?id=1130862662";
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:URL]];
        [request setHTTPMethod:@"POST"];
        
        NSHTTPURLResponse *urlResponse = nil;
        NSError *error = nil;
        NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
        
        NSDictionary *dic = [WXUtility objectFromJSON:results];
        NSArray *infoArray = [dic objectForKey:@"results"];
        
        if ([infoArray count]) {
            NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
            weakSelf.latestVer = [releaseInfo objectForKey:@"version"];
            if ([weakSelf.latestVer floatValue] > [currentVersion floatValue]) {
                if (![[NSUserDefaults standardUserDefaults] boolForKey: weakSelf.latestVer]) {
                    [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:weakSelf.latestVer];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New Version" message:@"Will update to a new version" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"update", nil];
                        [alert show];
                    });
                }
            }
        }
    });
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:self.latestVer];
            break;
        case 1:
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/weex-playground/id1130862662?mt=8"]];
        default:
            break;
    }
    [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
}

@end

自定义的weex组件-------具体跟js交互的文件

#import "WXLJCustomeEventModule.h"
#import <WeexSDK/WeexSDK.h>
#import "WXViewController.h"
#import "HomeViewController.h"

@interface WXLJCustomeEventModule()

@property (nonatomic, copy) WXModuleKeepAliveCallback loginSuccessCallBack;

@end

@implementation WXLJCustomeEventModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(openUrl:callback:))
WX_EXPORT_METHOD(@selector(close:callback:))
WX_EXPORT_METHOD(@selector(setNavBarTitle:callback:))

- (void)openUrl:(id)paramsJSON callback:(WXModuleKeepAliveCallback)callback
{
     NSDictionary *paramsDic = [CHUtil dictionaryWithJsonString:paramsJSON];
//    url: 'weex://go/ljDetail?orderId=123',
    if (paramsDic) {
        NSString *url = paramsDic[@"url"];
        NSDictionary *queryDic = [CHUtil getParamsDicWithUrl: url];
        
        if ([url hasPrefix:@"http"]) {
            WXViewController *vc = [[WXViewController alloc] initWithUrl:[NSURL URLWithString:url] useWeexEnv:YES];
            [[weexInstance.viewController navigationController] pushViewController:vc animated:YES];
        } else if ([url hasPrefix:@"weex"] && [url rangeOfString:@"ljDetail"].location != NSNotFound){
            
            HomeViewController *vc = [HomeViewController new ];
            vc.orderId = queryDic[@"orderId"];
            [[weexInstance.viewController navigationController] pushViewController:vc animated:YES];
            NSLog(@"url:%@", url);
            return;
        }
    }
    
}

- (void)close:(id)paramsJSON callback:(WXModuleKeepAliveCallback)callback
{
    [weexInstance.viewController.navigationController popViewControllerAnimated:YES];
    if (callback) {
        callback(@"", NO);
    }
}

 

2016-12-20 16:20:44 WangQingLei0307 阅读数 6494

首先,我们先来创建一个宏定义,如下

#define LABEL(x,y,w,h)        [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];

创建完成后,我们要看两个很重要的位置,LABEL(x,y,w,h)CGRectMake(x, y, w, h),我们可以看到,括号里的x,y,w,h,为四个变量参数,也就是说,带参数的宏定义,括号的内容必须要一直,参数对应,这样的话:

LABEL(0, 0, 50, 50

实际执行的错操作:

[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];

效果:

UILabel *page_numberL;

page_numberL = LABEL(005050);

这样我们就不需要再写好多墨迹的代码,例如:[UILabel alloc]initWithFrame:CGRectMake我们直接被一个  LABEL  代替了

 

2016-09-28 15:22:03 C_Lluckying 阅读数 2161

NSError的应用在实际开发中也是经常会接触到的,这是我在做登录界面的时候,我希望输入框输入完成后即刻判断输入是否正确,如果输入错误需要显示错误信息。
也想过用一个block里边装个数组@[BOOL,NSString]这样来完成需求,其实也是可以的。不过何不用用NSError呢?

下边我贴出了我定义的CheckManger(信息检测类):

在manager的头文件中

#import <Foundation/Foundation.h>

typedef void(^completed)(BOOL isCorrect, NSError *error);

@interface LLCheckManager : NSObject

/**验证手机号码是否正确*/
+ (void)checkPhoneNumber:(NSString *)phoneNumString completed:(completed) completed;

/**验证邮箱是否输入正确*/
+ (void)checkEmail:(NSString *)emailString completed:(completed)completed;

/**验证密码是否正确*/
+ (void)checkPassworld:(NSString *)passwordString completed:(completed)completed;

@end

在manager的m文件中:
首先需要知道NSError的构建参数,
1.domain:—— 错误域 (自定义,作用我不是很清楚暂且理解为提示作用吧)
2.code: —— 错误编码(自己定义,编码应当与错误内容匹配,相当于看到404就知道是访问不了)
3.userInfo:——错误原因(自己定义,给出错误的原因)

具体信息且看代码:

#import "LLCheckManager.h"

#define LLErrorDomain @" An Error Has Occurred"

typedef enum {
    LLErrorDefult = 0,
    LLErrorConnect   ,
    LLErrorNotFind,
    LLErrorMatch
}LLErrorFailed;

@implementation LLCheckManager

#pragma mark —— 定义错误
/**返回一个错误*/
+ (NSError *)errorWithCode:(LLErrorFailed)code{
    NSString * localizedDescription;
    switch (code) {
        case LLErrorConnect:
            localizedDescription = @"网络链接错误";
            break;
        case LLErrorNotFind:
            localizedDescription = @"没有找到";
            break;
            case LLErrorMatch:
            localizedDescription = @"匹配错误";
            break;
        default:
            localizedDescription = @"输入错误";
            break;
    }

    NSDictionary * userInfo = [NSDictionary dictionaryWithObject:localizedDescription forKey:NSLocalizedDescriptionKey];
    NSError * aError = [NSError errorWithDomain:LLErrorDomain code:code userInfo:userInfo];
    return aError;
}

#pragma mark —— 验证

/**验证手机号码*/
+ (void)checkPhoneNumber:(NSString *)phoneNumString completed:(completed)completed{

    NSString *phoneNumFormat = @"^1[2|3|4|5|6|7|8][0-9]{9}$";
    //表示字符串以1开头,紧接着是2、3、4、5、6、7、8中的任意一个,然后是0~9中的数字 以9个 结尾。

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumFormat];
    BOOL isMatch = [pred evaluateWithObject:phoneNumString];
    completed(isMatch,[self errorWithCode:LLErrorDefult]);
}

//验证邮箱
+ (void)checkEmail:(NSString *)emailString completed:(completed)completed{
    NSString * emailFormat = @"^(([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]";
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailFormat];
    BOOL isMatch = [pred evaluateWithObject:emailString];
    completed(isMatch,[self errorWithCode:LLErrorDefult]);
}

/**验证密码*/
+ (void)checkPassworld:(NSString *)passwordString completed:(completed)completed{
    NSString *passwordFormat = @"^[A-Za-z0-9]{6,20}+$";
    //表示字符串以大写字母 或 小写字母 或 数字 中的6到20个 组成
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCH %@",passwordFormat];
    BOOL isMatch = [pred evaluateWithObject:passwordString];
    completed(isMatch,[self errorWithCode:LLErrorDefult]);  
}

@end

在ViewController中如何用到error呢?

直接调用方法,和一般的error用法相同

#define mark —— textField Delegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [LLCheckManager checkPhoneNumber:textField.text completed:^(BOOL isCorrect, NSError *error) {
        if (isCorrect) {
            NSLog(@"账号输入正确");
        }else{
           // NSLog(@"%@",error);
          NSLog(@"%@",error.localizedDescription);
        }
    }];
}

iOS页面通过KVO传值

阅读数 1918

iOS之微信支付开发

阅读数 20637