技术开发iOS开发技术部落iOS开发

iOS开发中常用的方法(二)(持续更新)

2016-09-22  本文已影响675人  even_cheng

接上一篇 iOS开发中常用的方法(一)#

NSString常见用法:###

全部字符转为大写字母
-(NSString*)uppercaseString 

全部字符转为小写字母
-(NSString*)lowercaseString

把每个单词首字母大写,其他字母小写:
-(NSString*)capitalizedString

比较两个对象的内容是否相同:
-(BOOL)isEqualToString:(NSString*)aString

比较两个字符串内容(ASCII码)的大小:
-(NSComparisonResult)compare:(NSString*)string;
比较两个字符串的地址是否相同用"=="

忽略大小写进行比较:
-(NSComparisonResult)caseInsensitiveCompare:(NSString*)string;

有条件比较:
- (NSComparisonResult)compare:(NSString *)string options (NSStringCompareOptions)mask;  
options常用的三个条件:    
NSCaseInsensitiveSearch:忽略大小写    
NSLiteralSearch:默认的,全比较    
NSNumericSearch:字母还是比较ascii码,如果遇到数字,比较数字的大小(还是一位一位的比较) 
NSComparisonResult:枚举   
三个值:NSOrderedAscending(升序), NSOrderedSame, NSOrderedDescending(降序)   

判断是否sString开头:
-(BOOL)hasPrefix:(NSString*)sString;

判断是否sString结尾
-(BOOL)hasSuffix:(NSString*)sString;

检查字符串中是否包含sString:
-(NSRang)rangOfString:(NSString*)aString;

反方向搜索:
[str rangeOfString:@"str"options:NSBackwardsSearch];

从指定位置from开始截取到尾部:
-(NSString*)substringFormIndex:(NSUInteger)from;

从字符串的开头一直截取到指定位置to,但不包括该位置的字符:
-(NSString*)substringToIndex:(NSUInteger)to;

按照所给出的NSRange从字符串中截取字符串:
-(NSString*)substringWithRange:(NSRange)range;

用replacement替换target:
-(NSString*)stringByReplacingOccurrencesOfString:(NSSting*)target withString:(NSString*)replacement;

返回字符串长度:
-(NSUInteger)length;

返回index位置对应的字符:
-(unichar)characterAtIndex:(NSUInteger)index;

各种去掉: 
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set; 

去掉头尾空格
+ (id)whitespaceCharacterSet; 

去除所有的空格: 
[str stringByRep]acingOccurrencesOfString:@" "withString:@“”]

去掉头尾所有的小写字母 
+ (id)lowercaseLetterCharacterSet; 

去掉头尾所有的大写字母
+ (id)uppercaseLetterCharacterSet; 

去掉头尾的指定字符串
+ (id)characterSetWithCharactersInString:(NSString *)aString; 

常见文件操作###

这个文件或文件夹(目录)是否存在
- (BOOL)fileExistsAtPath:(NSString *)path;

 这个文件或文件夹是否存在, isDirectory代表是否为文件夹
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;

这个文件或文件夹是否可读
- (BOOL)isReadableFileAtPath:(NSString *)path;

这个文件或文件夹是否可写
- (BOOL)isWritableFileAtPath:(NSString *)path;

这个文件或文件夹是否可删除
- (BOOL)isDeletableFileAtPath:(NSString *)path;

获得这个文件\文件夹的属性
- (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error;

 查找给定路径下的所有子路径,返回一个数组,深度查找,不限于当前层,也会查找package的内容。
- (NSArray *)subpathsAtPath:(NSString *)path;

 获的的当前子路径下的所有直接子内容必须是一个目录
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;

创建文件
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attire;
 参数1:路径
 参数2:文件内容
 参数3:属性
  
创建文件夹(createIntermediates为YES代表自动创建中间的文件夹)
- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL) createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error;

拷贝,如果目标目录已经存在同名文件,则无法拷贝
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;

移动(剪切)移动文件
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;

删除文件
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;

异常捕捉:

(try catch并不能检测所有的错误)
例: b = NO;
@try  
//只能写一个
{ 
 int rezult = a/b;
//这里放的是有可能出错的代码
}  
@catch(NES xception *exception)   
//可以写多个
   {
     //此处放出错以后我们处理的代码
   }
@finally   
//只能写一个
{  
 printf("abcd\n");
//不管是否出错这行代码一定会执行
}

获取类的所有属性

+ (NSDictionary *)getPropertys
{
    NSMutableArray *proNames = [NSMutableArray array];
    NSMutableArray *proTypes = [NSMutableArray array];
    NSArray *theTransients = [[self class] transients];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        //获取属性名
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        if ([theTransients containsObject:propertyName]) {
            continue;
        }
        [proNames addObject:propertyName];
        //获取属性类型等参数
        NSString *propertyType = [NSString stringWithCString: property_getAttributes(property) encoding:NSUTF8StringEncoding];
       
        if ([propertyType hasPrefix:@"T@"]) {
            [proTypes addObject:SQLTEXT];
        } else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]||[propertyType hasPrefix:@"Tq"]||[propertyType hasPrefix:@"TQ"]) {
            [proTypes addObject:SQLINTEGER];
        } else {
            [proTypes addObject:SQLREAL];
        }
        
    }
    free(properties);
    
    return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];
}

获取沙盒路径

获取libraryCache路径

-(instancetype)appendCache
{
    return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.lastPathComponent];
}

获取Documents路径

-(instancetype)appendDocuments
{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.lastPathComponent];
}

获取Temp路径

-(instancetype)appendTemp
{
    return [NSTemporaryDirectory() stringByAppendingPathComponent:self.lastPathComponent];
}

XML解析

- (void)parserDidStartDocument:(NSXMLParser *)parser{ 
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{}
- (void)parserDidEndDocument:(NSXMLParser *)parser{}

XML解析第三方框架: GDataXMLElement

判断请求地址是否可用

  +(BOOL) pingUrl: (NSString *) urlStr {

  NSURL* URL = [NSURL URLWithString:urlStr];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  [request setHTTPMethod:@"HEAD"];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

  __block BOOL result;
  NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

      if (error) {

          result = NO;

      }else{

          result = YES;
      }

  }];

  [task resume];


  return result;
}

全局常量及宏定义

设置RGB颜色

#define RGB(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

弹框

#define HUD(text)  if (((NSString *)text).length > 0) {MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];hud.mode = MBProgressHUDModeText;hud.labelText = text;[hud setRemoveFromSuperViewOnHide:YES];[hud hide:YES afterDelay:1];}

导航栏标题

#define SET_NAV_TITLE(_TITLE) ({UILabel *titleLabel = [[UILabel alloc] init];titleLabel.backgroundColor = [UIColor clearColor];titleLabel.textColor = [UIColor whiteColor];titleLabel.text = _TITLE;titleLabel.font=[UIFont boldSystemFontOfSize:18];[titleLabel sizeToFit];self.navigationItem.titleView = titleLabel;})

导航栏返回按钮

#define SET_BACK_ITEM(_IMAGENAME) ({UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];[leftButton setFrame:CGRectMake(0, 0, 25, 25)];[leftButton setImage:[UIImage imageNamed:_IMAGENAME] forState:UIControlStateNormal];[leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown]; leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftButton];})

导航栏左右item

#define SET_NAV_ITEM(_TITLE,ISLEFT) ({UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];[navButton setFrame:CGRectMake(0, 0, 56, 56)];[navButton setTitle:_TITLE forState:UIControlStateNormal];[navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchDown];navButton.titleLabel.font = [UIFont systemFontOfSize:14];if(ISLEFT){navButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:navButton];} else {navButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:navButton];} })

判断是否是iOS8以上

#define iOS8Later ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

重定义NSLog

#define Log(format, ...) NSLog(@"%s--line:%d " format, __FUNCTION__, __LINE__, ##__VA_ARGS__)

UserDefaults

#define kUserDefaults [NSUserDefaults standardUserDefaults]
```
切换跟控制器的通知
```
#define kSwitchRootViewControllerNotification @"SwitchRootViewControllerNotification"
```
 Navigaiton高度
```
#define  NavBarHeight 64
```
屏幕高度
```
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
```
得到屏幕宽度
```
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
```
屏幕适配
```
#define kWidthValue(value) ((value)/375.0f*[UIScreen mainScreen].bounds.size.width)

#define kHeightValue(value) ((value)/667.0f*[UIScreen mainScreen].bounds.size.height)
```
判断是真机还是模拟器
```
#if TARGET_OS_IPHONE
//iPhone Device
#endif
 
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
```

打印日志
```
#ifdef DEBUG
#define LRLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#else
#define LRLog(...)

#endif
```
强弱引用
```
#define kWeakSelf(type)  __weak typeof(type) weak##type = type;
#define kStrongSelf(type)  __strong typeof(type) type = weak##type;
```

设置控件圆角边框
```
#define kBorderRadius(Obj, Radius, Width, Color)\
[Obj.layer setCornerRadius:(Radius)];\
[Obj.layer setMasksToBounds:YES];\
[Obj.layer setBorderWidth:(Width)];\
[Obj.layer setBorderColor:[Color CGColor]]
```

GCD
```
//GCD - 一次性执行
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);

//GCD - 在Main线程上运行
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);

//GCD - 开启异步线程
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
```

获取沙盒目录
```
//获取temp
#define kPathTemp NSTemporaryDirectory()
//获取沙盒 Document
#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//获取沙盒 Cache
#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
```

###获取成员变量
```
//定义一个保存成员变量个数的变量                            
unsignedint count = 0;                            
Ivar* ivars =  class_copyIvarList([obj class], &count);
//遍历成员列表找到需要的属性                                                       
for (int i = 0; i < count; i++)                            
{                                                               
//获取成员                               
 Ivar ivar = ivars[i];                                                               
//获取属性名                               
 constchar* name = ivar_getName(ivar);                               
//属性的类型                              
constchar * type = ivar_getTypeEncoding(ivar);                                                               
//转化成字符串                                
NSString* nameStr = [NSStringstringWithUTF8String:name];                                
NSString* typeStr = [NSStringstringWithUTF8String:type];                                NSLog(@"name:%@,type:%@",nameStr,typeStr);                                    
//给成员变量赋值                               
 if ([nameStr isEqualToString:@"_internalView"])                        
  {
   [obj setValue:imageView forKey:@"_internalView"];                                                               
  }
                          
}
```
###修改textField的placeholder的字体颜色、大小
```
self.textField.placeholder = @"请输入用户名";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
```
###计算两点距离
```
static __inline__ CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2) { CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y; return sqrt(dx*dx + dy*dy);}
```
###收起键盘的相关方法
```
1、点击键盘的Return收起键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField { return [textField resignFirstResponder]; }

2、点击View收起键盘
[self.view endEditing:YES];

3、统一收起键盘
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
```
###获取当前硬盘空间
```
NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *fattributes = [fm attributesOfFileSystemForPath:NSHomeDirectory() error:nil];

    NSLog(@"容量%lldG",[[fattributes objectForKey:NSFileSystemSize] longLongValue]/1000000000);
    NSLog(@"可用%lldG",[[fattributes objectForKey:NSFileSystemFreeSize] longLongValue]/1000000000);
```
###将UIColor转为UIImage
```
- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return theImage;
}
```
###SDWebImage清理缓存
```
// 清理内存
[[SDImageCache sharedImageCache] clearMemory];

// 清理webview 缓存
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config.URLCache removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeAllCachedResponses];

// 清理硬盘
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    [self.tableView reloadData];
}];
```
上一篇下一篇

猜你喜欢

热点阅读