iOS基础--一些常用的小知识(二)

清理缓存(具体情况还需要具体调整)

- (void)clearCache
{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"是否清理缓存" preferredStyle:UIAlertControllerStyleAlert] ;
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil] ;
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
            {
                // 拿到缓存路径
            NSString *cachePath = [SandBoxPaths cachePath] ;
                // 缓存路径下的各文件目录
            NSArray *filesArray = [[NSFileManager defaultManager] subpathsAtPath:cachePath] ;
            // 循环遍历各个路径
            for (NSString *path in filesArray)
            {
                NSError *error ;
                // 路径拼接
                NSString *filePath = [cachePath stringByAppendingPathComponent:path] ;
                if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
                {
                    // 如果存在该文件就删除
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error] ;
                }
            }
                [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES] ;
            }] ;
            [alertController addAction:cancleAction] ;
            [alertController addAction:okAction] ;
            [self.navigationController presentViewController:alertController animated:YES completion:nil] ;

}

// 提示清除缓存成功
- (void)clearCacheSuccess
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"清除缓存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] ;
    [alertView show] ;
}

计算缓存文件夹下缓存的大小.

//遍历文件夹获得文件夹大小,返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

代码延迟执行的方法

方法一(NSObject): [self performSelector:@selector(delayAction :) withObject:@"我5秒之后执行" afterDelay:5] ;
方法二 (GCD): dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"我只能坚持5秒") ;
    });

UIScrollView的常见属性

UIScrollView的属性总结
属性  作用
CGPoint contentOffSet   监控目前滚动的位置
CGSize contentSize  滚动范围的大小
UIEdgeInsets contentInset   视图在scrollView中的位置
iddelegate  设置协议
BOOL directionalLockEnabled     指定控件是否只能在一个方向上滚动
BOOL bounces    控制控件遇到边框是否反弹
BOOL alwaysBounceVertical   控制垂直方向遇到边框是否反弹
BOOL alwaysBounceHorizontal     控制水平方向遇到边框是否反弹
BOOL pagingEnabled  控制控件是否整页翻动
BOOL scrollEnabled  控制控件是否能滚动
BOOL showsHorizontalScrollIndicator     控制是否显示水平方向的滚动条
BOOL showsVerticalScrollIndicator   控制是否显示垂直方向的滚动条
UIEdgeInsets scrollIndicatorInsets  指定滚动条在scrollerView中的位置
UIScrollViewIndicatorStyle  设定滚动条的样式
float decelerationRate  改变scrollerView的减速点位置
BOOL tracking   监控当前目标是否正在被跟踪
BOOL dragging   监控当前目标是否正在被拖拽
BOOL decelerating   监控当前目标是否正在减速
BOOL delaysContentTouches   控制视图是否延时调用开始滚动的方法
BOOL canCancelContentTouches    控制控件是否接触取消touch的事件
float minimumZoomScale  缩小的最小比例
float maximumZoomScale  放大的最大比例
float zoomScale     设置变化比例
BOOL bouncesZoom    控制缩放的时候是否会反弹
BOOL zooming    判断控件的大小是否正在改变
BOOL zoomBouncing   判断是否正在进行缩放反弹
BOOL scrollsToTop   控制控件滚动到顶部

如何装载Storyboard中指定的ViewController?

  首先,需要指定ViewController的ID,和Storyboard ID一致。然后使用下面的代码:
 TabBarController *tabBarController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TabBarController"];

一句话实现系统的打电话功能.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];

检测网络变化

首先,导入#import "Reachability.h"
其次,添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    Reachability *hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier];

 观察者的回调实现:如果没有网络,跳到系统网络设置处
- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    switch (status)
    {
        case ReachableViaWiFi:
            // NSLog(@"====当前网络状态为Wifi=======");
            break;
        case ReachableViaWWAN:
            // NSLog(@"====当前网络状态为蜂窝=======");
            break;
            
        default:
            // NSLog(@"你是外星来的吗?");
            //警示框
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络,请检查!" preferredStyle:UIAlertControllerStyleAlert];
            //添加一个取消按钮
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
            {
                [self exitApplication] ;
            }] ;
            //添加一个确定按钮
            UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
            {
                NSURL *url = [NSURL URLWithString:@"prefs:root=WIFI"];
                if ([[UIApplication sharedApplication] canOpenURL:url])
                {
                    [[UIApplication sharedApplication] openURL:url];
                }
            }];
            //将创建好的action添加到警示框视图控制器上
            [alertController addAction:cancleAction] ;
            [alertController addAction:OKAction];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            break;
        }
    }
}

// 关闭app的动画
- (void)exitApplication {
    [UIView beginAnimations:@"exitApplication" context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:NO];
    [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
    self.view.bounds = CGRectMake(0, 0, 0, 0);
    [UIView commitAnimations];
}
// 关闭app
- (void)animationFinished:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([animationID compare:@"exitApplication"] == 0) {
        exit(0);
    }
}

coreData版本更新迭代时,需要在中if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]){} 把options后边的nil换成自定义的字典options,如下:

NSDictionary *options = @{NSInferMappingModelAutomaticallyOption:@"YES",NSMigratePersistentStoresAutomaticallyOption:@"YES"} ;

你可能感兴趣的:(iOS基础--一些常用的小知识(二))