iOS Tips

Xcode

收錄1

  • 用戶截屏?xí)r觸發(fā)
    UIApplicationUserDidTakeScreenshotNotification通知當(dāng)用戶截屏?xí)r會觸發(fā)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenCapture) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
- (void)screenCapture{
    // doSomething
}
  • About Exceptions Breakpoint
    蘋果官方文檔只介紹了這個斷點(diǎn)的使用方法,沒對這個斷點(diǎn)的功能做具體的介紹。
    當(dāng)應(yīng)用發(fā)生諸如數(shù)組越界、null值、對象重復(fù)釋放等問題導(dǎo)致的崩潰時,Xcode通常只會跳到main()函數(shù)。而Exceptions Breakpoint會在異常發(fā)生的時候在異常的地方放一個斷點(diǎn),調(diào)試器不會再跳到main()函數(shù),而是停留在了異常發(fā)生的地方,而且大多數(shù)情況下Exceptions Breakpoint都會打印異常消息。碉堡了!

如果將Exceptions設(shè)置為All,會導(dǎo)致應(yīng)用在main()函數(shù)里面崩潰,避免這個問題的方法是將Exception更改為Objective-C

  • 代碼繼續(xù)執(zhí)行,判斷方法執(zhí)行次數(shù)

    //底部automatically continue 一定要勾選
  • 神器計(jì)算圖片位置的函數(shù)
    AVMakeRectWithAspectRatioInsideRect()

通過這個函數(shù),我們可以計(jì)算一個圖片放在另一個 view 按照一定的比例居中顯示,可能說的我比較抽象,還是用圖來顯示,可以說它可以直接一個 image 以任何的比例顯示顯示在 imageview 中居中所處的位置,拿 UIViewContontAspectFit來演示

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];
imageView.center = self.view.center;
imageView.backgroundColor = [UIColor redColor];
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIImage *image = [UIImage imageNamed:@"mm.jpg"];
imageView.image = image;

 CGRect iamgeAspectRect = AVMakeRectWithAspectRatioInsideRect(image.size, imageView.bounds);
NSLog(@"iamgeAspectRect = %@, imageView =%@",NSStringFromCGRect(iamgeAspectRect),NSStringFromCGRect(imageView.frame));
[self.view addSubview:imageView];

******這個函數(shù)是在 AV框架*********
  • 在使用view的縮放的時候,layer.border.width隨著view的放大,會出現(xiàn)鋸齒化的問題,解決這個問題需要設(shè)置這個屬性。

    self.layer.allowsEdgeAntialiasing = YES;
    
  • Xcode 8.0 后運(yùn)行程序會有一堆無聊的打印(真機(jī)調(diào)試時取消對勾)


UIViewController

通過代碼為xib 或sb中view增加約束時盡量避免在viewDidLoad中執(zhí)行

-(void)updateViewConstraints {
     [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(64);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];

   //一定要先調(diào)記得super方法
    [super updateViewConstraints];
}

UINavigationController

  • navigationBar
    設(shè)置navigationBar透明度alpha為0,相當(dāng)于將navigationBar隱藏,則子視圖全部隱藏,相應(yīng)的標(biāo)題及左右按鈕全部失效。如果讓navigationBar透明,其它子視圖有效,則需下面方法。
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//消除橫線
[self.navigationController.navigationBar.shadowImage = [UIImage new];

當(dāng)然如果是要在上下劃動時改變透明度,則要如下方法

[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;//可以根據(jù)需要改變alpha
  • navigationBar 的transluent 默認(rèn)為YES,
    viewController 的EdgesForExtendedLayout 默認(rèn)為UIRectEdgeAll
    viewController 的automaticallyAdjustsScrollViewInsets 默認(rèn)YES,
    設(shè)為NO時,會從screen頂部開始。
    默認(rèn)情況下navigationBar是毛玻璃效果,并且視圖上的tableView
    從navigationBar下開始,不會出現(xiàn)遮擋,但cell數(shù)量較多時,顯示不全,所以要改變UIRectEdgeAll
[self setEdgesForExtendedLayout:UIRectEdgeTop];
  • 改變navigationBar的顏色
//這樣顯然是錯誤的
 self.navigationController.navigationBar.backgroundColor = [UIColor redColor];
//正確如下
1.
   [self.navigationController.navigationBar setBackgroundImage:           
   [self imageWithColor:[UIColor greenColor]] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
2.
    NSDictionary *textAttributes = @{
                   NSFontAttributeName: [UIFont   systemFontOfSize:18],
                   NSForegroundColorAttributeName: [UIColor whiteColor],
                               };
        UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];

        [navigationBarAppearance setBarTintColor:[UIColor greenColor]];//背景色
        [navigationBarAppearance setTitleTextAttributes:textAttributes];//標(biāo)題字體顏色
        [navigationBarAppearance setTintColor:[UIColor redColor]];//item顏色
        [navigationBarAppearance setTranslucent:NO];//是否毛玻璃
      
        //ios 9以前將狀態(tài)欄改成白色
       [UIApplication sharedApplication].statusBarStyle  = UIStatusBarStyleLightContent;
        //ios 9以后已經(jīng)變成了viewController 的對象方法,首先重寫
        -(UIStatusBarStyle)preferredStatusBarStyle{  return UIStatusBarStyleLightContent; }  
        其次info中添加View controller-based status bar appearance 并設(shè)置為NO即可。(好像也可以不重寫,直接)
  • pop頁面后暫不銷毀VC
//這樣做后簡單幾秒鐘后頁面可以不刷新,保持原樣 
  if (saveTaskVC ==nil) {

    TaskShowViewController * worksVC =[[TaskShowViewController alloc]init];

    saveTaskVC = worksVC;

    NSTimer * tiemr =[NSTimer scheduledTimerWithTimeInterval:10 repeats:NO block:^(NSTimer * _Nonnull timer) {
        saveTaskVC = nil;
        timer = nil;
        [timer invalidate];
    }];
}
[self.navigationController pushViewController:saveTaskVC animated:YES];

UITableView

  • 兩個方法:didDeselect 方法是指選中后再點(diǎn)其它c(diǎn)ell 時執(zhí)行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    _selectionIndexPath = indexPath; // 記錄被選中cell的indexPath,防止復(fù)用出現(xiàn)問題
    
    UIButton *checkMark = cell.subviews[2];
    [checkMark setImage:[UIImage imageNamed:@"danxuan_selected"] forState:UIControlStateNormal];
    NSLog(@"中時:%ld",indexPath.row);
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
    NSLog(@"未選中時:%ld",indexPath.row);
}
  • UItableview 默認(rèn)是UITableViewStylePlain 樣式,區(qū)頭區(qū)尾會有停滯效果。取消停滯如下
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = sectionHead.height;  
   if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView;.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if(scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

當(dāng)然也可直接改樣式為 UITableViewStyleGrouped,需要設(shè)置tableHeaderView的高度,否則頭部會有空白,所以必須寫

tableView.tableHeaderView =[ [UIView alloc]initWithFrame:CGRectMake(0,0,width,0.1)]

處理TableView中cell點(diǎn)擊延遲

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];(不能為YES!!)
}

  • 分割線頂著邊線,這樣寫更合適
-(void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

UIGestureRecognizer

  • UISwipeGestureRecognizer/UIPanGestureRecognizer區(qū)分
    在同一個View上添加swipe 和 Pan 兩個手勢,只走Pan手勢,完全不走 swipe.所以要實(shí)現(xiàn)以下兩個方法:
//1.優(yōu)先識別后者
[panGesture requireGestureRecognizerToFail:swipeGesture];
//2.實(shí)現(xiàn)手勢的代理方法
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer *)otherGestureRecognizer {
      return YES;
} 
  • 禁止側(cè)滑返回
網(wǎng)上其它方法好像效果都不理想,這個簡單直接
  id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];

Button

  • 自定義Button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 button.frame = CGRectMake(0, 0, 30, 30);
 button.center = self.view.center;
 [button setTitle:@"+" forState:UIControlStateNormal];
 button.titleLabel.font = [UIFont systemFontOfSize:30];
 [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 3, 2, 2)];
 button.layer.cornerRadius = 15;
 button.layer.masksToBounds = YES;
 button.backgroundColor = [UIColor redColor];
 [self.view addSubview:button];
 [button addTarget:self action:@selector(goAction:) forControlEvents:UIControlEventTouchUpInside];
  • 屏蔽點(diǎn)擊
button.enabled = NO; 會改變按鈕的狀態(tài),顏色變灰
button.userInteractionEnabled = NO ; 按鈕的狀態(tài)不改變,顏色不改變
  • UIEdgeInsets
 //可以設(shè)置圖片文字適當(dāng)偏移
 UIEdgeInsets inset = UIEdgeInsetsMake(100, 50, 0, 0);
 btn.titleEdgeInsets = inset;
 btn.imageEdgeInsets = inset;
  • 取消點(diǎn)擊效果
self.Button.adjustsImageWhenHighlighted = NO;

UITextField

  • PlaceHolder
//設(shè)置占位字體大小及顏色 
[textField setValue: [UIColor colorWithWhite:0.800 alpha:1.000] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue: [UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
//一般占位字符會偏上
// 實(shí)測需要先設(shè)置字體然后居中才有效
 textField.font = [UIFont systemFontOfSize:12];
 textField.contentVerticalAlignment =
        UIControlContentVerticalAlignmentCenter;

UIView

  • 獲取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;
}
  • 當(dāng)View的值為透明或半透明時,其子視圖也會改變透明度。為了讓子視圖不透明,可以有以下方法
bgView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5];
bgView.backgroundColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.4 alpha:0.5];
bgView.backgroundColor = [color colorWithAlphaComponent:0.5]; //實(shí)例方法
  • UIView設(shè)置圖片
//可能會耗內(nèi)存
UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)];
 UIColor *myColor  = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0.png"]];
myView.backgroundColor = myColor;

UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)];
UIImage *image = [UIImage imageNamed:@"0"];
myView.layer.contents = (__bridge id)image.CGImage;
//取值范圍0-1,對應(yīng)x,y,width,height.
myView.layer.contentsCenter = CGRectMake(0, 0, 1, 1);
  • 陰影設(shè)置
self.bgView.layer.cornerRadius = 5;
//當(dāng)設(shè)置陰影時下面這句一定要注釋
// self.bgView.layer.masksToBounds = YES;
self.bgView.layer.shadowColor = [UIColor grayColor].CGColor;
self.bgView.layer.shadowOffset = CGSizeMake(0, 1);
self.bgView.layer.shadowOpacity = 0.3;
self.bgView.layer.shadowRadius = 2;

模態(tài)跳轉(zhuǎn)

  FFViewController *VC = [[FFViewController alloc]init];
// UIModalTransitionStylePartialCurl;  //翻頁
// UIModalTransitionStyleCrossDissolve;//漸顯
  VC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; //旋轉(zhuǎn)
 [self presentViewController:VC animated:YES completion:nil];

Layer

  • 指定邊切圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:myImage.bounds //bounds不是frame
                                                  byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft
                                                        cornerRadii:CGSizeMake(2, 2)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = myImage.bounds;
    maskLayer.path = maskPath.CGPath;
    myImage.layer.mask = maskLayer;
  • 設(shè)置顏色漸變
  CAGradientLayer*layer = [CAGradientLayer layer];  // 設(shè)置漸變效果
  CAGradientLayer *layer  = [[CAGradientLayer alloc]init];
  layer.frame = self.testView.bounds;
  layer.colors = [NSArray arrayWithObjects:(id)[UIColor redColor].CGColor,[UIColor clearColor].CGColor, nil];
  //默認(rèn)從上到下排列顏色
 layer.startPoint = CGPointMake(0, 0);
 layer.endPoint = CGPointMake(1, 1);
[self.testView.layer addSublayer:layer];

UIImage

  • 縮放
//可以實(shí)現(xiàn)對圖片拉伸,并減少形變
UIEdgeInsets inset = UIEdgeInsetsMake(50,50,50,50);
image = [image resizableImageWithCapInsets:inset resizingMode:UIImageResizingModeStretch];
  • 模糊層
//毛玻璃效果
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];  
//毛玻璃效果視圖  
  UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];

 blurEffectView.frame = self.mageView.frame;
 [self.imageView insertSubview:blurEffectView atIndex:0];
  • contentModel

自定義彈窗

  • 簡單彈窗
AlertViewController *alertVC = [[AlertViewController alloc]init];
UIWindow *window = [UIApplication sharedApplication].keyWindow;[window.rootViewController addChildViewController: alertVC];
[window.rootViewController.view addSubview: alertVC.view];
//然后在相應(yīng)的VC中設(shè)置背景,處理手勢
-(void)viewDidLoad{
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBtn:)];
     tap.delegate = self;
     [self.view addGestureRecognizer:tap]; 
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if(touch.view == self.view){
        return YES;
    }else
        return NO;
}
  • 系統(tǒng)彈窗
//彈出選項(xiàng)框可以畫也可以用系統(tǒng)的
-(void)go:(UIButton *)sender{
    TestViewController *testVC = [[TestViewController alloc] init];
    // 設(shè)置大小
    testVC.preferredContentSize = CGSizeMake(150, 300);
    // 設(shè)置 Sytle
    testVC.modalPresentationStyle = UIModalPresentationPopover;
    // 需要通過 sourceView 來判斷位置的
    testVC.popoverPresentationController.sourceView =sender;
    // 指定箭頭所指區(qū)域的矩形框范圍(位置和尺寸),以sourceView的左上角為坐標(biāo)原點(diǎn)
    // 這個可以 通過 Point 或  Size 調(diào)試位置
    testVC.popoverPresentationController.sourceRect = sender.bounds;
    // 箭頭方向
    testVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    // 設(shè)置代理
    testVC.popoverPresentationController.delegate = self;
    [self presentViewController:testVC animated:YES completion:nil];
}
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller{
    return UIModalPresentationNone; //不適配
}
-(BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController{
    return YES;   //點(diǎn)擊蒙版popover消失, 默認(rèn)YES
}

UIAppearance

  • 簡單應(yīng)用
//修改導(dǎo)航欄背景圖
UINavigationBar * appearance = [UINavigationBar appearance];
UIImage *navBackgroundImg =[UIImage imageNamed:@"navBg.png"];
[appearance setBackgroundImage:navBackgroundImg forBarMetrics:UIBarMetricsDefault];
//個性導(dǎo)航欄返回按鈕
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
self.title=[NSString stringWithFormat:@"第%lu頁",(unsigned long)self.navigationController.viewControllers.count];
//自定義返回按鈕
UIImage *backButtonImage = [[UIImage imageNamed:@"fanhui.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//將返回按鈕的文字position設(shè)置不在屏幕上顯示
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
//修改導(dǎo)航條上的UIBarButtonItem
UIBarButtonItem *appearance = [UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil];
//設(shè)置導(dǎo)航欄的字體包括backBarButton和leftBarButton,rightBarButton的字體
NSDictionary *textAttributes = @{UITextAttributeFont: [UIFont systemFontOfSize:18],
                                 UITextAttributeTextColor: [UIColorblueColor],
                                 UITextAttributeTextShadowColor: [UIColor whiteColor],
                                 UITextAttributeTextShadowOffset: [NSValue valueWithCGSize:CGSizeMake(1, 1)]};
[appearance setTitleTextAttributes:textAttributes forState:1];//forState為0時為下正常狀態(tài),為1時為點(diǎn)擊狀態(tài)。
//修改leftBarButton,rightBarButton背景效果
[appearance setBackgroundImage:[UIImage imageNamed:@"navBarButton.png"]
                      forState:UIControlStateNormal
                         style:UIBarButtonItemStyleBordered
                    barMetrics:UIBarMetricsDefault];
[appearance setBackgroundImage:[UIImage imageNamed:@"navBarButton_a.png"]
                      forState:UIControlStateHighlighted
                         style:UIBarButtonItemStyleBordered
                    barMetrics:UIBarMetricsDefault];
//修改底部欄
UITabBar *appearance = [UITabBar appearance];
//設(shè)置背景圖片
[appearance setBackgroundImage:[UIImage imageNamed:@"tabbar_bg.png"]];
//設(shè)置選擇item的背景圖片
UIImage * selectionIndicatorImage =[[UIImage imageNamed:@"tabbar_slider"]resizableImageWithCapInsets:UIEdgeInsetsMake(4, 0, 0, 0)] ;
[appearance setSelectionIndicatorImage:selectionIndicatorImage];
  • 注意事項(xiàng)
-(IBAction)SegmentChange:(UISegmentedControl *)sender {
    
    NSLog(@"%ld",(long)sender.selectedSegmentIndex);
    switch (sender.selectedSegmentIndex) {
        case 0:
            [UISwitch appearance].onTintColor = [UIColor redColor];
            break;
        case 1:
            [UISwitch appearance].onTintColor = [UIColor blueColor];
            break;
        case 2:
            [UISwitch appearance].onTintColor = [UIColor blackColor];
            break;
        default:
            break;
    }
    //因?yàn)樵谔砑幽且豢桃呀?jīng)添加了屬性,隨意移除后從新添加
    [self.view removeFromSuperview];
    
    //添加
    [[UIApplication sharedApplication].keyWindow addSubview:self.view];
}

NSString

  • 字符串拼接圖片
 -(NSAttributedString *)attatchImage: (UIImage *)image atLastOfString: (NSString *)string{
    //1.現(xiàn)將內(nèi)容string轉(zhuǎn)化為NSMutableAttributedString
    NSMutableAttributedString *attributedMString = [[NSMutableAttributedString alloc] initWithString:string];    
    //2.獲取圖片的NSTextAttachment
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = image;  
    //在這里如果不設(shè)置attatchment的bounds,就有可能造成添加的圖片的位置高于文字或者大小與文字的大小不統(tǒng)一的情況。不過還是具體問題具體分析,在這里只是告訴各位圖片的rect是可以更改的
    attach.bounds = CGRectMake(2, -2, 15, 15);    
    //3.將圖片的NSTextAttachment轉(zhuǎn)化為imageString
    NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attach];

    //4.合并NSMutableAttributedString和imageString
    [attributedMString appendAttributedString:imageString];

    //5. 將NSMutableAttributedString轉(zhuǎn)化為NSAttributedString并返回
    return [[NSAttributedString alloc] initWithAttributedString:attributedMString]
}
  • 按多個字符分割
NSString *str = @"2,3.4";
 NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@",."];
 NSLog(@"%@",[str componentsSeparatedByCharactersInSet:set]);

NSArray

  • 數(shù)級快速求和平均值最大最小
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);

UIDatePicker

  • 當(dāng)設(shè)置最大最小時間時必須設(shè)置時區(qū)
  [_picker  setTimeZone:[NSTimeZone localTimeZone]];//必須設(shè)置時區(qū)最大小最小值才有用
  _picker.minimumDate = [NSDate dateWithString:@"1949-01-20" format:@"yyyy-MM-dd"];
_picker.maximumDate = [NSDate date];

其它

  • 使用SDWebImage時就做好在系統(tǒng)內(nèi)存警告時釋放內(nèi)容的準(zhǔn)備
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDWebImageManager sharedManager] cancelAll];
}

//清理緩存時類似
- (IBAction)clickClearButton:(UIButton:)sender {
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
}
  • 禁止鎖屏
[UIApplication sharedApplication].idleTimerDisabled = YES;
  • 使用 xib 時如有多個相同類型控件,如多個button,label 可拉出一個包含這種類型控件的數(shù)組


  • 隨機(jī)數(shù)

 arc4random()范圍太大,下面這更合適
//生成0 - 255 的隨機(jī)數(shù)
 CGFloat r = arc4random_uniform(256) / 255.0;
 CGFloat g = arc4random_uniform(256) / 255.0;
 CGFloat b = arc4random_uniform(256) / 255.0;
  • load & initialize
在程序啟動時,Runtime會去加載所有的類。
在這一時期,如果類或者類的分類實(shí)現(xiàn)了+load方法,
則會去調(diào)用這個方法。
+initialize方法是在類或子類第一次接收消息之前會被調(diào)用,
這包括類的實(shí)例對象或者類對象。
如果類一直沒有被用到,則這個方法不會被調(diào)用。
因此,我們可以將類使用時所需要的一些前置條件在這兩個方法中處理。
但應(yīng)該盡量放在+initialize中。
因?yàn)?load方法是在程序啟動時調(diào)用,勢必會影響到程序的啟動時間。
而+initialize方法可以說是懶加載調(diào)用,只有用到才會去執(zhí)行。
  • nil/NSNull
nil:指向一個對象的空指針
當(dāng)一個對象置為nil時,這個對象的內(nèi)存地址就會被系統(tǒng)收回。

NULL:指向其他類型(如:基本類型、C類型)的空指針
從C語言繼承來的,就是一個簡單的空

NSNull:通常表示集合中的空值
[NSNull null]和nil的區(qū)別在于,
nil是一個空對象,已經(jīng)完全從內(nèi)存中消失了
NSNull對象擁有一個有效的內(nèi)存地址

對NSNull對象發(fā)送消息會crash
對nil 發(fā)消息則不會crash

數(shù)組中可能有 [NSNull null],但不能為nil
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內(nèi)容