iOS-开发

iOS 记不住的代码段

2016-09-13  本文已影响20人  26b5cc676194

1.没有自动装箱的masonry的使用

 // 自动布局 在这之前需要想把控件添加到父控件中
    [_segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.mas_equalTo(40);
    }];

    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.mas_equalTo(_segmentedControl.mas_bottom).offset(10);
    }];

    [_noMessagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.mas_equalTo(_segmentedControl.mas_bottom).offset(10);
    }];

2.获取系统返回pop手势

- (void)addScreenGesture {
    // 1.获取系统自带滑动手势的target对象
    id target = self.navigationController.interactivePopGestureRecognizer.delegate;
    // 2.创建全屏滑动手势,调用系统自带手势的target的滑动方法
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
    // 3.给控制器的view添加全屏滑动手势
    [self.view addGestureRecognizer:panGesture];
}

3.忽略未使用变量警告

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
UIView *eTestView = [[UIView alloc] init];
#pragma clang diagnostic pop

4.忽略方法未声明警告

#pragma
clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
   UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]
initWithTarget:targetaction:@selector(handleNavigationTransition:)];
#pragma
clang diagnostic pop

5.忽略任意警告

Snip20160913_3.png

结合上面忽略警告的方式,以后你会忽略警告了吗?

忽略一个类文件的警告

Snip20160913_4.png

6.在APPDelegate中禁用第三方键盘

#pragma mark - 禁用第三方键盘
- (BOOL)application:(UIApplication
*)application shouldAllowExtensionPointIdentifier:(NSString
*)extensionPointIdentifier {
    return NO;
}

7.Alert提示宏定义

#define Alert(_S_, ...) [[[UIAlertView
alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__]
delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show]

8.不使用typedef定义block的方式使用block


- (void)isIdentify:(void(^)(BOOL identify, NSError *error))finished;

9.NSDateFormatter的线程安全优化方法

static NSString *const kCurrentDateFormatter = @"currentDateFormatter";

+ (instancetype)dateFormatter {
    NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
    WLDateFormatter *dateFormatter = threadDict[kCurrentDateFormatter];

    if (!dateFormatter) {
        @synchronized (self) {
            if (!dateFormatter) {
                dateFormatter = [WLDateFormatter new];
                threadDict[kCurrentDateFormatter] = dateFormatter;
                return dateFormatter;
            }
            return dateFormatter;
        }
    }
    return dateFormatter;


    static id _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [WLDateFormatter new];
    });

    return _instance;
}

10.字符串去掉空格

NSString *str = @" 王启镰 王俨 王迅 王朝 ";// 去掉所有的空格NSString *replaceStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];// 去掉前后的空格NSString *characterSetStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];


11.打印字符串地址

 strK = @"This is a String!";
 NSLog(@"strK = %p", strK);

12.设置圆角的优化

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:view];

view.layer.cornerRadius = 8;
view.layer.masksToBounds = YES;
view.layer.shouldRasterize = YES;
view.layer.rasterizationScale = [UIScreen mainScreen].scale;

13.数字处理,尽量使用高精度的double

NSString *str = @"123456789.99";
CGFloat floatN = [str floatValue];
double doubleN = [str doubleValue];
NSLog(@"floatN = %f", floatN);
 NSLog(@"doubleN = %f", doubleN);
/* 打印结果
2016-07-13 17:22:24.673 WYTestDemo[12699:4390961]
floatN = 123456792.000000
2016-07-13 17:22:24.673 WYTestDemo[12699:4390961]
doubleN = 123456789.990000
**/

14.获取启动图的名称[项目启动后会对launchImage中的图片进行2次命名]

- (NSString *)fetchLaunchImageName
{
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict) {
        if(CGSizeEqualToSize(CGSizeFromString(dict[@"UILaunchImageSize"]),[UIScreen mainScreen].bounds.size))
        {
            return dict[@"UILaunchImageName"];
        }
    }
    return nil;
}

15.字符串包含iOS7.0适配

NSString *text = @"10.5%~12.25%";
// iOS 8专有API
BOOL isContainsPercent = [textcontainsString:@"%@"];
// 如果要支持iOS7 请用这个
BOOL isContain = [@"%" rangeOfString:self.text].length > 0;

16.获取UIWebView的JSContext

JSContext *context = [self.secondPage valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"sendUrl"] = ^{
        NSArray *args = [JSContext currentArguments];
        if(args.count > 0){
            WLWebController *webVC = [[WLWebController alloc] init];
            webVC.url = [NSString stringWithFormat:@"%@",args[0]];
            [self.navigationController pushViewController:webVC animated:YES];
        }
    };

17.约束优先级

Snip20160913_5.png

Content Compression Resistance Priority,也叫内容压缩阻力优先级(小名:别挤我),该优先级越高,则越晚轮到被压缩。
Content Hugging Priority,也叫内容紧靠优先级(小名:别扯我),该优先级越高,这越晚轮到被拉伸。

18. 选中tabBar的跳转,先选中tabBar,把当前导航控制器popToRootViewController,然后用选中tabBar的导航控制器push出一个页面

// 这里的mainVC 的类型是UITabBarController
mainVC.selectedIndex = 0;
[weakSelf.navigationController popToRootViewControllerAnimated:NO];
WLBFinanceViewController
*finance = [[WLBFinanceViewController alloc] init];
finance.pageType= kFinancePageTypeStandard;
[mainVC.viewControllers[0] popToRootViewControllerAnimated:NO];
[mainVC.viewControllers[0] pushViewController:financeanimated:YES];

19.在iOS中一个汉字占3个字节

20.模拟器真机判断


#if TARGET_IPHONE_SIMULATOR //模拟器

#elif TARGET_OS_IPHONE //真机

#endif

21.使用SDWebImage保存图片到本地

[[SDImageCache sharedImageCache] storeImage:image forKey:imageUrl];

22.给UIWebView设置请求头

NSDictionary *dictionnary =@{@"UserAgent":userAgent};
 [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

23.获取UIWebView的UserAgent

UIWebView *tempWebView = [[UIWebView alloc]init];
NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

24.NSArray和NSDictionary去除NSNull处理

static id WYJSONObjectByRemovingNullValues(id JSONObject) {
    if ([JSONObject isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
        for (id value in (NSArray *)JSONObject) {
            [mutableArray addObject:WYJSONObjectByRemovingNullValues(value)];
        }

        return mutableArray.copy;
    } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
        for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
            id value = (NSDictionary *)JSONObject[key];
            if (!value || [value isEqual:[NSNull null]]) {
                [mutableDictionary removeObjectForKey:key];
            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
                mutableDictionary[key] = WYJSONObjectByRemovingNullValues(value);
            }
        }

        return mutableDictionary.copy;
    }

    return JSONObject;
}

25.Xcode中支持的模拟器所在的位置

**/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

26.NSNumber可以自动去掉小数点后边的0**

double number = 60000.00;
NSLog(@"number = %@", @(number));
/* 打印结果
2016-08-23 17:22:13.988 NSAttributeString换行[5256:259641] number = 60000
**/
 // 特殊情况
NSString *str = @"8.54";
double number = [str doubleValue];
NSLog(@"number = %@", @(number));
/* 打印结果
**2016-08-25 18:10:57.988 ****绘制虚线****[20270:1205620] number = 8.539999999999999**
**/

27.对数字类型进行判断

int number = 2.00;
NSNumber *myNumber = @(number);
if (strcmp([myNumberobjCType], @encode(double)) == 0) {
    NSLog(@"我是double");
} else if (strcmp([myNumber objCType], @encode(int)) == 0) {
    NSLog(@"我是int");
} else if (strcmp([myNumber objCType], @encode(float)) == 0) {
    NSLog(@"我是float");
} else if (strcmp([myNumber objCType], @encode(BOOL)) == 0) {
    NSLog(@"我是BOOL");
}

28.定义和使用C语言数组

CGFloat colHeight[5];
for (int i =0; i< 5; ++i){
    colHeight[i] = i;
}

29.NSRunLoop的正确开启方式

BOOL shouldKeepRunning = YES; // global NSRunLoop *theRL = [NSRunLoop currentRunLoop]; while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);/** 在需要关闭运行循环的地方设置shouldKeepRunning为No即可.因为如果直接使用[NSRunLoop run]当移除输入源过后,不能保证运行循环能够终止.*/

30.屏幕尺寸

1.屏幕大小
iPhone4做原型时,可以用320×480
iPhone5做原型时,可以用320×568
iPhone6做原型时,可以用375×667
iPhone6Plus原型,可以用414×736

2.屏幕分辨率
iPhone4的显示分辨率,640×960
iPhone5的显示分辨率,640×1136
iPhone6的显示分辨率,1334×750
iPhone6 Plus显示为,1920×1080

31.页面不添加标记进行一次性判断

if (objc_getAssociatedObject(self, _cmd)) {
  NSLog(@"已经加载过啦");
} else {
  objc_setAssociatedObject(self, _cmd, @"Launch", OBJC_ASSOCIATION_RETAIN);
  NSLog(@"第一次加载");
}

上一篇下一篇

猜你喜欢

热点阅读