基础知识(二)

来源:互联网 发布:mysql 主键索引作用 编辑:程序博客网 时间:2024/06/17 23:56

基础知识(二)

1 . NSDate 时间的计算

  • 获取现在的时间: NSDate *dateNow = [NSDate date]; // @“2015-11-10 10:01:01” 输出的是这种格式的
  • 计算从什么时间~什么时间(一段时间): NSTimeInterval periodTime = [[NSDate date] timeIntervalSinceDate : dateNow];
    // 把要计算的代码运行时间放在这两句代码中间
  • 时间转时间戳: NSTimeInterval time = [[NSDate date] timeIntervalSince1970] // 时间戳是NSTimeInterval型,也是long型
  • 时间戳转时间: NSDate *date = [NSDate dateWithTimeIntervalSince1970:time]
  • 时间戳转字符串: NSString *timeSp = [NSString stringWithFormat:@"%d", (long)[time timeIntervalSince1970]];
  • 字符串转时间戳: NSTimeInterval time = [timeSp longLongValue];
  • 设置时间的显示格式和将 NSDate 转成 NSString

    NSDate *select = [NSDate date];NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"yyyy-MM-dd"];   // 想要获取凌晨的时间:设置为@"yyyy-MM-dd 00:00:00”即可; 设置年月日时分秒格式的时间:@“yyyy-MM-dd HH:mm:ss”  hh和HH区别:分别表示12小时制,24小时制NSString *dateS =  [dateFormatter stringFromDate:select];
  • 时间的比较:可以用时间戳直接比较: if ([string longLongValue] < time)
  • 获取当前时间的年、月、日、时、分、秒 :

    NSDate *now = [NSDate date]; // 获取当前时间NSCalendar *calendar = [NSCalendar currentCalendar];NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];NSUInteger year = [dateComponent year];    // 年NSUInteger month = [dateComponent month];   // 月NSUInteger day = [dateComponent day];       // 日NSUInteger hour = [dateComponent hour];     // 时NSUInteger minute = [dateComponent minute]; // 分NSUInteger second = [dateComponent second]; // 秒

2 . ARC与非ARC转换

添加 -fobjc-arc : 让原来不支持ARC 的使用ARC
添加 -fno-objc-arc : 让原来支持ARC的不使用ARC

3 . NSIntegerint 区别 以及 NSUInteger、NSNumber

  • NSInteger 会根据系统的位数(32or64)自动选择 int 的最大数值(int or long)。当需要使用 int 类型的变量的时候,可以用 int ,也可以用 NSInteger
  • typedef unsigned int NSUInteger; // 这是NSInteger的定义
  • NSUInteger 是无符号的,即没有负数, NSInteger 是有符号的
  • NSNumber 是一个类,其余的是基本类型

    例如:[array addObject:3] //这种写法是错误的     [array addObject:[NSNumber numberWithInt:3]] // 这种写法是正确的

4 . 数据类型及对应字节数、位数?

32位操作系统中: int是4个字节,32位,每个字节占8位。
char 是1个字节、char* 是4个字节、float 是4个字节、double 是8个字节、long 是4和字节、long long 是8个字节、unsigned long 是4个字节;
64位操作系统中: char是1个字节、char* 是8个字节、int 是4个字节、float 是4个字节、double 是8个字节、long 是8个字节、long long 是8个字节、unsigned long 是8个字节

5 . 轻量级: 一般指规模较小,或者功能较为完善,比如mysql数据库和orcal数据库比较,前者就属于轻量级。

6 . UIPasteBoard :粘贴板

7 . 字符串拼接

stringByAppendingString: // 需要手动在名称前加“/”stringByAppendingPathComponent: // 不需要    例如:  NSString *imagePath = [skinPath stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]]; // 是在skinPath加后缀的意思NSString *imagePath = [skinPath stringByAppendingPathComponent:imageName]; // 是在skinPath后面加上“/”号连接imageName让它成为完整的路径

8 . 监控 UITableViewUIScrollView 上下滑动时触发某个方法(例如:上下滑动时关闭键盘)

UIScrollView 的代理方法:-(void)scrollViewDidScroll:(UIScrollView *)scrollView;
用这个方法之前要先实现 UIScrollViewDelegate
由于 UITableView 继承自 UIScrollView,所以只要实现 UITableViewDelegate,即可使用上面 UIScrollView 的代理方法.

9 . UITableViewDelegate 的两个参数

@required : 必须实现的代理方法 , 若没定义两个参数,则默认是必须实现的代理方法;
@optional : 不必须实现的代理方法;

一般定义 delegate 属性都是用 assign,防止循环circular count产生


例如:@property(nonatomic, assign) id<UITableViewDelegate>delegate;

10 . nilNilNULLNSNUll 的理解

  • nil :给对象赋值一般使用 object=nil ,表示把这个对象释放掉。称为“空对象”。对于这种空对象,所有关于 retain 的操作都会引起程序崩溃,例如字典添加键值或数组添加新元素等。

    id objectnil;[array addObject : object]; // 这种写法是错误的
  • NSNull : 和 nil 区别在于,nil 是一个空对象,已经从内存中消失了,若想表达“我们需要有一个容器,但这个容器里什么也没有”的观念时,就用 NSNull ,称为 “值为空的对象”NSNull 这个类继承 NSObject ,只有一个 “+(NSNull *)null” ;类方法。这说明 NSNull 对象拥有一个有效的内存地址,所以在程序中对它的任何引用都不会导致程序崩溃。

    if(object = nil) { object = [NSNull null]; } //  [NSNull null]是一个对象[array addObject:object] ; // 相比较上面一种写法, 这种写法是正确的
    • NilnilNil 在使用上没有严格规定,凡是使用 nil 的地方都可以用 Nil 来代替,反之亦然。只不过我们约定俗成的将 nil 表示一个空对象,Nil 表示一个空类。
    NSString *string = nil;Class classA = Nil;
    • NULLObject-C 来源于C、支持于C,也有别于C。而 NULL 就是C语言的语法,它表示一个空指针。一般赋值给 nil 之外的其他空值,如SEL
    int *point = NULLnil是一个对象指针为空,Nil是一个类指针为空,NULL是基本类型为空

11 . 音频播放 AudioservicesPlaySystemSound : 对于简单的、无混音音频,可以使用这个函数来播放简单的声音

12 . 正则表达式

正则表达式,又称正规表示法,是对字符串操作的一种逻辑公式。正则表达式可以检测给定的字符串是否符合我们定义的逻辑,也可以从字符串中获取我们想要的特定部分。

13 . UIToolBar:工具栏

UIToolBar 是我们经常用的控件之一。例如:在 navigation bar 上面加一个 UIToolBar,在 view 的底部加一个 UIToolBar,在键盘的上面加一个 UIToolBar

14 . UIViewAutoresizing autoresizingMask

 UIViewAutoresizingNone : superview变换时,自己不做变换  UIViewAutoresizingFlexibleTopMargin: 上边距弹性可变,下边距保持不变 UIViewAutoresizingFlexibleWidth:控件的宽度随着父视图的宽度按比例改变 UIViewAutoresizingFlexibleHeight:上边距不变,和superview在高度上变化同等高度。比如,superview加高100,则自己也加高100

15 . va_list

iOS实现传递不定长的多个参数点方法是使用 va_listva_list 的使用需要注意:

  • 首先在函数里定义 va_list 型的变量,这个变量是指向参数的指针
  • 然后用 va_start 初始化刚定义的 va_list 变量
  • 然后用 va_arg 返回可变的参数,va_arg 的第二个参数是你要返回的参数的类型,如果函数有多个可变参数的,依次调用 va_arg 获取各个参数
  • 最后用 va_end 宏结束可变参数的获取

    例如:

    +(void) functionName:(NSObject *)string,…{      va_list args; // 定义一个指向个数可变的参数列表指针      va_start (args, string) ; // string为第一个参数,也就是最右边的已知参数,这里就是获取第一个可选参数的地址      if (string) {           NSString *otherString;          while ((otherString = va_arg (args, NSString *))) { // 返回参数列表中指针所指的参数,返回类型为NSString,并使参数指针指向参数列表中下一个参数                // 依次获取所有参数          }      }      va_end (args); // 清空参数列表,并置参数指针args无效}

16 . NSTextContainer、NSLayoutManager、NSTextStorage

这是 UITextViewiOS7新增加的类。

  • NSTextStorage:保存并管理 UITextView 要展示的文字内容,该类是NSMutableAttributedString 的子类,由于可以灵活地往文字添加或修改属性,所以非常适用于保存并修改文字属性。
  • NSLayoutManager:用于管理 NSTextStorage 其中的文字内容的排版布局。
  • NSTextContainer:定义了一个矩形区域用于存放已经进行了排版并设置好属性的文字

17 . 获取键盘高度
http://www.cnblogs.com/qingjoin/archive/2012/09/12/2681659.html
http://blog.csdn.net/lwq421336220/article/details/32073633

添加两个通知,监听 UIKeyboardWillShowNotificationUIKeyboardWillHideNotification 状态,在弹起键盘和隐藏键盘时,和键盘输入法变更后高度变更,willshow监听会再次收到通知

18 . 判断字符串是否包含某个字符

  • if ([text rangeOfString:@"\n"].location != NSNotFound) {
    }
  • [text containsString : @“\n”]; // 这是8.0之后才有的API,手机系统低于8.0则会出错

19 . 关联:是指把两个对象相互关联起来,使得其中的一个对象作为另一个对象的一部分。

关联特性只有在Mac OS X V10.6以及以后的版本上才是可用的;
使用关联我们可以不用修改类的定义而为其对象增加存储空间;

  • 创建关联:objc_setAssociatedObject:该函数需要四个参数:源对象、关键字、关联的对象、关联策略. 关键字是一个 void 类型的指针,每个关联的关键字必须是唯一的,通常采用静态变量来作为关联策略表明了相关的对象是通过赋值、保留引用还是复制的方式进行关联的,还有这种关联是原子的还是非原子的
  • 获取相关联的对象:objc_getAssociatedObject
  • 断开关联:objc_setAssociatedObject :传入 nil 值即可
  • 使用 objc_removeAssociatedObject 可以断开所有关联。通常情况下不建议使用这个函数,因为他会断开所有关联。只有在需要把对象恢复到“原始状态”的时候才会使用这个函数

    例:把一个字符串关联到一个数组    static char overviewKey;    NSArray *array = [[NSArray alloc] initWithObjects:@“one”, @“two”, @“three”, nil];    NSString *overview = [[NSString alloc] initWithFormat:@“%@”, @“first three numbers”];    objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);    NSString *associatedObject = (NSString *) objc_getAssociatedObject(array, &overviewKey);    objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);

20 . scrollsToTop

scrollsToTopUIScrollView 的一个属性,主要用于点击设备的状态栏时,使 scrollsToTop == YES 的控件滚动返回至顶部。

每一个默认的 UIScrollView 的实例,他的 scrollsToTop 属性默认为 YES,所以要实现某一 UIScrollView 的实例点击设备状态栏返回顶部,则需要关闭其他的 UIScrollView 的实例的scrollsToTop 属性为 NO

很好理解:若多个 scrollView 响应返回顶部的事件,系统就不知道到底要将那个 scrollView 返回顶部了,因此也就不做任何操作了。

21 . 获取某个控件在另一个控件上的位置

 - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view; 例如:CGRect rect = [moreBtn convertRect:moreBtn.bounds toView:tableView];       // 获取moreBtn在tableview上的位置

22 . UITableViewheaderView 跟随 cell 的内容一起滚动

首先看看 tableView 有几个表头,如果只有一个,不要用 tableViewdelegate 来设置。直接自己定义一个 view ,赋给 tableviewtableHeaderView 就可以了(tableView.tableHeaderView = view)

23 . [UIApplication sharedApplication].keyWindow 添加视图无效

因为这个时候 appdelegate 中的 keywindow 还没有创建成功,将上面代码修改为[[[UIApplication sharedApplication] delegate] window] 即可

24 . UITextViewUITextField 区别

  • UITextView 支持多行输入并且可以滚动显示浏览全文,而 UITextField 只能单行输入。
  • UITextView 继承自 UIScrollView , UITextField 继承自 UIView[UIControl]
  • UITextview 没有 placeholder 属性 UItextFieldplaceholder属性

    在使用上我们完全可以把UITextView看作是UITextField的加强版。

25 . 修改 UITextFieldplaceHolder 字体颜色

  • 第一种

    UIColor *color = [UIColor whiteColor];  _userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"用户名" attributes:@{NSForegroundColorAttributeName: color}];  
  • 第二种

    [_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"]; 

26 . 创建一个悬浮的按钮(类似于网页上的“回到顶部”按钮)

UIButton *publishBtn = [ [UIButton alloc] init];[publishBtn bringSubviewToFront:_tableView]; // 按钮悬浮在tableView上

27 . contentSizeconentOffsetcontentInset 区别

  • contentSizescrollview 可以滚动的区域,比如 frame = (0 ,0 ,320 ,480) contentSize = (320 ,960) ,代表你的 scrollview 可以上下滚动,滚动区域为 frame 大小的两倍。
  • contentOffsetscrollview 当前显示区域顶点相对于 frame 顶点的偏移量,比如上个例子你拉到最下面,contentoffset 就是(0 ,480),也就是y偏移了480
  • contentInsetscrollviewcontentview 的顶点相对于 scrollview 的位置,例如你的 contentInset = (0 ,100) ,那么你的 contentview 就是从 scrollview 的(0 ,100)开始显示

28 . UITableViewCell 显示最底部的 cell

 //如果tableView返回多个section,每个section中只有1个row,则在[tableView reloadData]后,加上    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:_tableDataArr.count - 1];      if (indexPath.section < [self numberOfSectionsInTableView:tableView]) {          [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];      }// 如果tableView返回1个section,每个section中有多个row,则在[tableViewreloadData]后,加上    NSIndexPath *indexPath = [NSIndexPath indexPathForRow: _tableDataArr.count - 1 inSection:0];      if (indexPath.row < [tableView numberOfRowsInSection:0]) {         [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];      }

29 . UIButton 设置四周的颜色

  button.layer.borderWidth = 0.5; // 先设置四周边距的宽度  button.layer.borderColor = [UIColor BlackColor].CGColor; // 再设置边距颜色

30 . NSString stringWithFormat: 可以对数值进行四舍五入

  [NSString stringWithFormat:@“%.2f”, @“1.01003”]; // 1.01  [NSString stringWithFormat:@“%.2f”, @“1.01503”]; // 1.02  [NSString stringWithFormat:@“%.2f”, @“1.01403”]; // 1.01  [NSString stringWithFormat:@“%.2f”, @“1.01003”]; // 1.01

// 对数字转字符串的处理,对数字只舍不入NSRoundDown,例如:0.126 = 0.12

    // price:需要处理的数字, position:保留小数点第几位    - (NSString *)notRounding:(float)price afterPoint:(int)position{        NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];        NSDecimalNumber *ouncesDecimal;        NSDecimalNumber *roundedOunces;        ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];        roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];        return [NSString stringWithFormat:@"%@",roundedOunces];    }    调用:  float s =0.126;           NSString *sv = [self notRounding:s afterPoint:2];           NSLog(@"sv = %@",sv);           输出结果为:sv = 0.12

31 . 缩放动画

  self.focusBtn.transform = CGAffineTransformMakeScale(1.0f, 1.0f);  [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];  [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; //InOut 表示进入和出去时都启动动画  [UIView setAnimationDuration:5]; //动画时间  self.focusBtn.transform=CGAffineTransformMakeScale(0.01f, 0.01f); //先让要显示的view最小直至消失  [UIView commitAnimations]; //启动动画

或者:

 self.focusBtn.layer.anchorPoint = CGPointMake(0.5, 0.5); [self setAnchorPoint:CGPointMake(0, 0.5) forView:self.focusBtn]; self.focusBtn.transform = CGAffineTransformMakeScale(1.0f, 1.0f); [UIView animateWithDuration:1.0 animations:^{      self.focusBtn.transform=CGAffineTransformMakeScale(0.01f, 0.01f);    } completion:^(BOOL finished) {     self.focusBtn.hidden = YES;     self.iconBgImage.frame = CGRectMake(0, bigMargin, iconBgW, iconWH);     UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.iconBgImage.w, iconWH) byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(iconBgRadius, iconBgRadius)];     CAShapeLayer *maskLayer = [CAShapeLayer layer];     maskLayer.frame = CGRectMake(0, 0, self.iconBgImage.w, iconWH);     maskLayer.path = bezierPath.CGPath;     self.iconBgImage.layer.mask = maskLayer; }];    - (void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view{    CGPoint oldOrigin = view.frame.origin;    view.layer.anchorPoint = anchorPoint;    CGPoint newOrigin = view.frame.origin;    CGPoint transition;    transition.x = newOrigin.x - oldOrigin.x;    transition.y = newOrigin.y - oldOrigin.y;    view.center = CGPointMake (view.center.x - transition.x, view.center.y - transition.y); }

32 . 立体旋转动画

CABasicAnimation* rotationAnimation; rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"]; // 围绕着y轴旋转 rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ]; rotationAnimation.duration = 1.2; rotationAnimation.cumulative = YES; rotationAnimation.repeatCount = MAXFLOAT; [self.buttonTitle.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; // 添加动画 [self.buttonTitle.layer removeAnimationForKey:@"rotationAnimation"]; // 移除动画
1 0
原创粉丝点击