iOS零碎知识点

1、调用代码使APP进入后台,达到点击Home键的效果。(私有API)
[[UIApplication sharedApplication] performSelector:@selector(suspend)];
2、退出app程序(不推荐使用,这种方式会让用户觉得app闪退)
- (void)exitApplication {
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
       exit(0);
        }];
}
3、CGAffineTransformIdentity
1.CGAffineTransformMakeTranslation(CGFloat tx, CGFloat ty)(平移:设置平移量)

2.CGAffineTransformMakeScale(CGFloat sx, CGFloat sy)(缩放:设置缩放比例)仅通过设置缩放比例就可实现视图扑面而来和缩进频幕的效果。

3.CGAffineTransformMakeRotation(CGFloat angle)(旋转:设置旋转角度)

以上3个都是针对视图的原定最初位置的中心点为起始参照进行相应操作的,在操作结束之后可对设置量进行还原:

view.transform=CGAffineTransformIdentity;

CGAffineTransformIdentity:清空所有的设置的transform(一般和动画配合使用,只能使用于transfofrm设置的画面)
4、透过UIView
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.passthroughTouches) { // 是否可以透过view
        return [super pointInside:point withEvent:event];
    }
    for (UIView *subview in self.subviews) {
        if (subview.isHidden) {
            continue;
        }
        CGPoint subviewPoint = [self convertPoint:point toView:subview];
        if ([subview pointInside:subviewPoint withEvent:event]) {
            return YES;
        }
    }
    return NO;
}
5、class、superclass、super、self
class:获取方法调用者的类名;

superclass:获取方法调用者的父类类名;

super:编译修饰符,不是指针,跟const类似于关键字的作用,指向父类的标志;

本质还是拿到当前对象去掉用父类的方法;

self:是一个指针,有地址;
6、删除一个view好还是隐藏一个view好
修改一个视图的frame,或者是将视图从父视图上移除会直接导致调用该视图的layoutSubviews方法,而且如果设置了contentMode为UIViewContentModeRedraw的话,也会导致调用drawRect方法。此时如果你自定义了这俩个方法来做一些绘制和布局工作,将会消耗CPU和GPU来做你的工作。
因此,如果仅仅是为了隐藏视图的话,直接使用hidden属性即可。
7、weakSelf和strongSelf
Apple 官方的建议是,传进 Block 之前,把 ‘self’ 转换成 weak automatic 的变量,
这样在 Block 中就不会出现对 self 的强引用。如果在 Block 执行完成之前,self 被释
放了,weakSelf 也会变为 nil。

示例代码:
__weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [weakSelf doSomething];
});
clang 的文档表示,在 doSomething 内,weakSelf 不会被释放。但,下面的情况除外:

__weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [weakSelf doSomething];
    [weakSelf doOtherThing];
});
在 doSomething 中,weakSelf 不会变成 nil,不过在 doSomething 执行完成,调用第二个方法 doOtherThing 的时候,weakSelf 有可能被释放,于是,strongSelf 就派上用场了:
__weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf doSomething];
        [strongSelf doOtherThing];
    }
});
__strong (不加__strong时默认就是强引用) 确保在 Block 内,strongSelf 不会被释放。

总结
在 Block 内如果需要访问 self 的方法、变量,建议使用 weakSelf。
如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。

8、/usr/local is not writable 解决方法
sudo chown -R $(whoami):admin /usr/local
homebrew 安装cocoapods时如果当前版本过低要先执行一下命令
brew unlink cocoapods 
然后再重新安装

9、右滑返回问题
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer isEqual:self.navigationController.interactivePopGestureRecognizer]) {
        [self handleBackButtonClickEvent]; // 返回要处理的事情
    }
    return NO;
}
10、如何把一个CGPoint存入数组里

方法1:

CGPoint  itemSprite1position = CGPointMake(100, 200);
NSMutableArray * array  = [[NSMutableArray alloc] initWithObjects:NSStringFromCGPoint(itemSprite1position),nil];
    //    从数组中取值的过程是这样的:   
CGPoint point = CGPointFromString([array objectAtIndex:0]);

方法2:

CGPoint  itemSprite1position = CGPointMake(100, 200);
NSValue *originValue = [NSValue valueWithCGPoint:itemSprite1position];
NSMutableArray * array  = [[NSMutableArray alloc] initWithObjects:originValue, nil];
//    从数组中取值的过程是这样的:
NSValue *currentValue = [array objectAtIndex:0];
CGPoint point = [currentValue CGPointValue];
11、UIColor 获取 RGB 值
UIColor *color = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", components[3]);
12、求两点间的距离
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);
}
13、UITableViewCell indentationLevel 使用
UITableViewCell 属性 NSInteger indentationLevel 的使用, 对cell设置 indentationLevel的值,可以将cell 分级别。

还有 CGFloat indentationWidth; 属性,设置缩进的宽度。

总缩进的宽度: indentationLevel * indentationWidth
14、APP 屏蔽 触发事件
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
14、NSDictionary 转 NSString
NSDictionary *parametersDic = @{
                                @"key1":@"hahah",
                                @"key2":@"alpha"
                                };
    
    NSData *jsonData = parametersDic == nil ? nil : [NSJSONSerialization dataWithJSONObject:parametersDic options:0 error:nil];
    NSString *requestBody = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
15、获取某个view所在的控制器
- (UIViewController *)viewController {
    UIViewController *viewController = nil;  
    UIResponder *next = self.nextResponder;
    while (next) {
        if ([next isKindOfClass:[UIViewController class]]) {
            viewController = (UIViewController *)next;      
            break;    
    }    
        next = next.nextResponder;  
  } 
    return viewController;
}
16、两种方法删除NSUserDefaults所有记录
//方法一
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];
}
17、字符串反转
第一种:
- (NSString *)reverseWordsInString:(NSString *)str {    
    NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
    for (NSInteger i = str.length - 1; i >= 0 ; i --) {
        unichar ch = [str characterAtIndex:i];       
        [newString appendFormat:@"%c", ch];    
    }    
     return newString;
}
 
//第二种:
- (NSString*)reverseWordsInString:(NSString*)str {    
     NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];    
     [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { 
          [reverString appendString:substring];                         
      }];    
     return reverString;
}
18、禁止锁屏
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
19、字符串按多个符号分割
NSString *str = @"abc,vee.yyyuu";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@",."];
NSArray * strArray = [str componentsSeparatedByCharactersInSet:set];
20、iOS 获取汉字的拼音
- (NSString *)transform:(NSString *)chinese {
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    NSLog(@"%@", pinyin);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    //返回最近结果
    return pinyin;
}

21、获取实际使用的LaunchImage图片
- (NSString *)getLaunchImageName {
    CGSize viewSize = self.window.bounds.size;
    // 竖屏    
    NSString *viewOrientation = @"Portrait";  
    NSString *launchImageName = nil;    
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict) {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) {
            launchImageName = dict[@"UILaunchImageName"];        
        }    
    }    
    return launchImageName;
}
22、判断view是不是指定视图的子视图
BOOL isView = [textView isDescendantOfView:self.view];
23、NSArray 快速求总和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
24、监测IOS设备是否设置了代理,需要CFNetwork.framework
NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);
    
NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);
    
if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
    NSLog(@"没代理");
} else {
    NSLog(@"设置了代理");
}
25、UIImage 占用内存大小
UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);

26、防止scrollView手势覆盖侧滑手势
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

27、字符串中是否含有中文
- (BOOL)checkIsChinese:(NSString *)string {
    for (int i=0; i
28、dispatch_group的使用
dispatch_group_t dispatchGroup = dispatch_group_create();
    dispatch_group_enter(dispatchGroup);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"第一个请求完成");
        dispatch_group_leave(dispatchGroup);
    });
 
    dispatch_group_enter(dispatchGroup);
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"第二个请求完成");
        dispatch_group_leave(dispatchGroup);
    });
 
    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
        NSLog(@"请求完成");
    });
29、UITextField每四位加一个空格,实现代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 四位加一个空格
    if ([string isEqualToString:@""]) {
        // 删除字符
        if ((textField.text.length - 2) % 5 == 0) {
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    } else {
        if (textField.text.length % 5 == 0) {
            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
        }
    }
    return YES;
}
30、方法- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
功能:

  把textField中位置为range的字符串替换为string字符串;

  此函数在textField内容被修改时调用;

返回值:

  YES,表示修改生效;NO,表示不做修改,textField的内容不变。

参数说明:

  textField:响应UITextFieldDelegate协议的UITextField控件。

  range:    UITextField控件中光标选中的字符串,即被替换的字符串;

          range.length为0时,表示在位置range.location插入string。

  string:   替换字符串;

          string.length为0时,表示删除。


31、获取手机安装的应用
- (void)getAppFromPhone {
    Class c =NSClassFromString(@"LSApplicationWorkspace");
    id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
    NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
    for (id item in array) {
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
    }
}
32、判断两个rect是否有交叉
if (CGRectIntersectsRect(rect1, rect2)) {
}
33、判断一个字符串是否为数字
NSString *str = @"1111";
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
        NSLog(@"是数字");
 } else {
        NSLog(@"不是数字");
 }
34、将一个view保存为pdf格式
- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename {    
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();
    [aView.layer renderInContext:pdfContext];
    UIGraphicsEndPDFContext();
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

35、判断某一行的cell是否已经显示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
未完待续。。。

你可能感兴趣的:(iOS零碎知识点)