Objective-C使用部分技巧

一:避免Block的Retain Cycle

1.__block ASIHTTPRequest* request=[ASIHTTPRequestrequestWithURL:url];
            __weak ASIHTTPRequest* request2=request;
            
2.ASIHTTPRequest* request=[ASIHTTPRequestrequestWithURL:url];
     ASIHTTPRequest*  __weak  request2=request;

二:返回当前时间精确到秒作为图片名

NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
//[formatter setDateFormat:@"YYYY.MM.dd.hh.mm.ss"];//秒
//[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];//毫秒

[formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
NSString* nsStringCurrentTime = [formatter stringFromDate:[NSDate date]];
//NSLog(@"当前时间:%@", nsStringCurrentTime);

三:屏蔽NSLog

#define NSLog(...) {};

#endif

四:长按手势的判定,防止出现两次

- (void)longPressGestureRecognizer:(UILongPressGestureRecognizer *)sender {
	//对手势状态进行判断 否则出现两次
	if (sender.state == UIGestureRecognizerStateEnded){
		UIActionSheet *actionSheet =[ [UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"不了" destructiveButtonTitle:nil otherButtonTitles:@"删除草稿",@"清空草稿箱",nil];
		//将cell的Tag值传给actionSheet,确定哪个cell触发了行为
		actionSheet.tag = sender.view.tag;
		[actionSheet showInView:self.tabBarController.view];
	}
}

五:如无必要不要重载视图的生命周期方法,即使写出来什么代码都没添加

比如viewWillAppear,loadView........否则可能引发严重的BUG

六:UITableViewStyleGrouped 头部多余一部分的取消

UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(CGFLOAT_MIN, CGFLOAT_MIN, CGFLOAT_MIN, CGFLOAT_MIN);
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableHeaderView:view];
    [tableView setTableFooterView:view];
以空白视图替换头部视图

七:对UIDatePicker选择的日期进行 format。

对UIDatePicker选择的日期进行 format。
1)当你的format格式是
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // 这里是用大写的 H
NSString* dateStr = [dateFormatter stringFromDate:date];
你获得就是24小时制的。
2)当你的format格式用的是
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; // 这里是用小写的 h
你获得的就是12小时制的。

八:限制输入长度

-(BOOL)textField:(nonnull UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(nonnull NSString *)string
{
//    NSLog(@"%@",string);
    //可变
    NSMutableString *string0 = [NSMutableString stringWithString:textField.text];
    //替换成字符形式这是必须的步骤
    [string0 replaceCharactersInRange:range
                           withString:string];
    if (string0.length>11)
    {
        return NO;
    }

    return YES;
}

猜你喜欢

转载自blog.csdn.net/baicai_520/article/details/85317342