IOS开发问题索引(六)

全系列文章索引:

IOS开发问题索引(一)

IOS开发问题索引(二)

IOS开发问题索引(三)

IOS开发问题索引(四)

IOS开发问题索引(五)

IOS开发问题索引(六)

IOS开发问题索引(七)

IOS开发问题索引(八)

IOS开发问题索引(九)


1 计算指定时间与当前的时间差

计算指定时间与当前的时间差

http://blog.csdn.net/xinshou_jiaoming/article/details/7068328

    计算指定时间与当前的时间差 比如,3天前、10分钟前(这个在项目中经常遇到,所以记录了下来)

以下是实现方法:

/**

 *计算指定时间与当前的时间差

 *@paramcompareDate   某一指定时间

 *@return 多少(秒or分or天or月or年)+前 (比如,3天前、10分钟前)

*/

+(NSString *) compareCurrentTime:(NSDate*) compareDate

{

    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];

    timeInterval = -timeInterval;

    long temp = 0;

     NSString*result;

    if (timeInterval < 60) {

      result = [NSStringstringWithFormat:@"刚刚"];

    }

    else if((temp = timeInterval/60) <60){

        result = [NSStringstringWithFormat:@"%d分前",temp];

    }

    else if((temp = temp/60) <24){

      result = [NSStringstringWithFormat:@"%d小前",temp];

    }

  else if((temp = temp/24) <30){

      result = [NSStringstringWithFormat:@"%d天前",temp];

    }

  else if((temp = temp/30) <12){

      result = [NSStringstringWithFormat:@"%d月前",temp];

    }

  else{

      temp = temp/12;

      result = [NSStringstringWithFormat:@"%d年前",temp];

    }

  return result;

}

以下是NSDate中的常用方法:

/**

- (id)initWithTimeInterval:(NSTimeInterval)secs sinceDate:(NSDate*)refDate;

  初始化为以refDate为基准,然后过了secs秒的时间

- (id)initWithTimeIntervalSinceNow:(NSTimeInterval)secs;

  初始化为以当前时间为基准,然后过了secs秒的时间

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;

  以refDate为基准时间,返回实例保存的时间与refDate的时间间隔

- (NSTimeInterval)timeIntervalSinceNow;

  以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔

- (NSTimeInterval)timeIntervalSince1970;

  以1970/01/01 GMT为基准时间,返回实例保存的时间与1970/01/01 GMT的时间间隔

- (NSTimeInterval)timeIntervalSinceReferenceDate;

  以2001/01/01 GMT为基准时间,返回实例保存的时间与2001/01/01 GMT的时间间隔

+ (NSTimeInterval)timeIntervalSinceReferenceDate;

*/

  //秒

// - (NSTimeInterval)timeIntervalSinceNow;

//    以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔


2  IOS开发常用数学函数

1、 三角函数

  double sin (double);正弦

  double cos (double);余弦

  double tan (double);正切

2 、反三角函数

  double asin (double); 结果介于[-PI/2,PI/2]

  double acos (double); 结果介于[0,PI]

  double atan (double); 反正切(主值), 结果介于[-PI/2,PI/2]

  double atan2 (double,

double); 反正切(整圆值), 结果介于[-PI,PI]

3 、双曲三角函数

  double sinh (double);

  double cosh (double);

  double tanh (double);

4 、指数与对数

  double exp (double);求取自然数e的幂

  double sqrt (double);开平方

  double log (double); 以e为底的对数

  double log10 (double);以10为底的对数

  double pow(double x, double y);计算以x为底数的y次幂

  float powf(float x, float y);功能与pow一致,只是输入与输出皆为浮点数

5 、取整

  double ceil (double); 取上整

  double floor (double); 取下整

6 、绝对值

  double fabs (double);求绝对值

  double cabs(struct complex znum) ;求复数的绝对值

7 、标准化浮点数

  double frexp (double f, int*p); 标准化浮点数, f = x * 2^p, 已知f求x,p ( x介于[0.5,1] )

  double ldexp (double x, int p); 与frexp相反, 已知x,p求f

8 、取整与取余

  double modf (double, double*); 将参数的整数部分通过指针回传, 返回小数部分

  double fmod (double, double);返回两参数相除的余数

9 、其他

  double hypot(double x, double y);已知直角三角形两个直角边长度,求斜边长度

  double ldexp(double x, int exponent);计算x*(2的exponent次幂)

  double poly(double x, int degree, double coeffs [] );计算多项式

  int matherr(struct exception *e);数学错误计算处理程序

转载:http://blog.csdn.net/zyc851224/article/details/7843859


3 IOS获取屏幕尺寸与分辨率

IOS获取屏幕分辨率

http://blog.csdn.net/tangaowen/article/details/7597535

        获取屏幕分辨率是个很有用的功能,尤其在一些游戏相关的开发中,图形的绘制与屏幕分辨率密不可分。得到当前屏幕的分辨率是必不可少的支持。

        获取屏幕分辨率可以两步走

1、得到当前屏幕的尺寸:

CGRect rect_screen = [[UIScreenmainScreen]bounds];

CGSize size_screen= rect_screen.size;

2、获得scale:

CGFloat scale_screen = [UIScreenmainScreen].scale;

        此时屏幕尺寸的宽高与scale的乘积就是相应的分辨率值。


4  iPhone开发分辨率

1.iPhone5分辨率320x568,像素640x1136,@2x

2.iPhone6分辨率375x667,像素750x1334,@2x

3.iPhone6 Plus分辨率414x736,像素1242x2208,@3x

        这里所注的都是已经添加相关尺寸loading图后的开发分辨率和像素数,其中iphone6 plus最终的物理分辨率会被苹果自动缩放到1080p(缩放比例1.14)。

iPhone6分辨率与适配

http://www.cocoachina.com/ios/20140912/9601.html


5 【编译】Cannotassign to 'self' outside of a method in the init family

        有时候我们重写父类的init方法时不注意将init后面的第一个字母写成了小写,在这个方法里面又调用父类的初始化方法(self = [super init];)时会报错,错误信息如下:error:Cannot assign to 'self' outside of a methodin the init family

        原因:只能在init方法中给self赋值,Xcode判断是否为init方法规则:方法返回id,并且名字以init+大写字母开头+其他  为准则。例如:-(id) initWithXXX;

出错代码:

-(id) Myinit{

    self = [super init];

    ……

}

解决方法:

-(id) initWithMy

{

    self = [super init];

}

如下代码:

       仅仅因为大小写问题,将initWithDelegate写成了-(id) initwithDelegate,就会报错


6 CoreData临时实体对象

NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([IMUserInfoEntity class]) inManagedObjectContext:[[IMDataModelCoreDataStorage shareInstance] mainThreadManagedObjectContext]];

    IMUserInfoEntity *userTmpEntity = [[IMUserInfoEntity alloc] initWithEntity: entity insertIntoManagedObjectContext: nil];


7 【Storyboard】在Storyboard中添加子View后,页面控件不显示问题

问题:

       在Storyboard的一个ViewController中添加子View后,再在代码中新建一个子View来替代此View,导致在代码中添加按钮控件,按钮不显示,但是可以接收到按钮事件。

//初始化地图View

    if (!_bMapView) {

        _bMapView  = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_BOUNDS.size.width, SCREEN_BOUNDS.size.height * 0.05)];//300 [[BMKMapView alloc]

initWithFrame:CGRectMake(0, 0, 320, 480)];

    }

    self.mapView = _bMapView;

    if (![self.view.subviews containsObject:self.mapView]) {

        [self.view addSubview:self.mapView];

    }

    UIButton *_provinceButton = [[UIButton alloc] initWithFrame:CGRectMake(120, 120, 100, 40)];

    _provinceButton.titleLabel.text = @"TestButton";

    _provinceButton.titleLabel.textColor = [UIColor yellowColor];

    [_provinceButton addTarget: self action: @selector(TestprovinceButtonClicked:) forControlEvents: UIControlEventTouchUpInside];

    [self.view addSubview: _provinceButton];

解决方案:

       在Storyboard的ViewController中添加的子View已经实例化了,通过简单地替换操作,不会使其实例自动释放,因为已经作为子View,添加进ViewController所在的View中了。需要手动先将其从SuperView移除,然后再重新添加新View的实例。

    //初始化地图View

    if (!_bMapView) {

        _bMapView  = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_BOUNDS.size.width, SCREEN_BOUNDS.size.height * 0.05)];//300 [[BMKMapView alloc]

initWithFrame:CGRectMake(0, 0, 320, 480)];

    }

    if (self.mapView) {

        [self.mapView removeFromSuperview];

    }

    self.mapView = _bMapView;

    if (![self.view.subviews containsObject:self.mapView]) {

        [self.view addSubview:self.mapView];

    }


8 【控件】UIButton控件文字不显示

//此行页面不会显示文字

_provinceButton.titleLabel.text = @"Test Button";

//此行页面显示文字

 [_provinceButtonsetTitle:@"Test1" forState:UIControlStateNormal];

9 【CoreData】like查询

查询不到结果写法

//    NSPredicate*predicate=[NSPredicate predicateWithFormat:@"province LIKE '%@?' AND cityLIKE '%@?' AND county =%@",tempEntity.province, tempEntity.city, tempEntity.county];

可查询到结果写法:

NSString *predStr = [NSString stringWithFormat:@"province LIKE \'%@?\' AND city LIKE \'%@?\' AND county = \'%@\'",tempEntity.province, tempEntity.city, tempEntity.county];

NSPredicate*predicate = [NSPredicate predicateWithFormat: predStr];

NSString * predStr = [NSString stringWithFormat:@"province LIKE \'%@%%\' AND city LIKE \'%@%%\' AND county = \'%@\'",tempEntity.province, tempEntity.city, tempEntity.county];


10 iOS字符串 中包含%百分号的方法

iOS 字符串 中包含 % 百分号的方法

    百分号的转换,NSString中需要格式化的字符串中百分号使用%%表示,而char*中百分号也是使用%%表示。

    例如:NSLog(@"%%%@%%",@"hello"),控制台会打印出%hello%。

11 【UILabel】自适应高度和自动换行

//初始化label  

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];  

//设置自动行数与字符换行  

[label setNumberOfLines:0];  

label.lineBreakMode = UILineBreakModeWordWrap;   

// 测试字串  

NSString *s = @"这是一个测试!!!adsfsaf时发生发勿忘我勿忘我勿忘我勿忘我勿忘我阿阿阿阿阿阿阿阿阿阿阿阿阿啊00000000阿什顿。。。";  

UIFont *font = [UIFont fontWithName:@"Arial" size:12];  

//设置一个行高上限  

CGSize size = CGSizeMake(320,2000);  

//计算实际frame大小,并将label的frame变成实际大小  

CGSize labelsize = [s sizeWithFont: font constrainedToSize: size lineBreakMode: UILineBreakModeWordWrap];  

[label setFrame:CGRectMake:(0, 0, labelsize.width, labelsize.height)];  


IOS7以上做法

http://www.tuicool.com/articles/eYbAv2

UILabel自适应高度和自动换行

http://blog.csdn.net/csj1987/article/details/6662852

iOS学习5:UILabel的使用

http://bbs.9ria.com/thread-244444-1-1.html


12 Mac上颜色提取工具

        很多人有这个需求:把鼠标放在一个点上,显示该点颜色的RGB值。其实苹果电脑的Mac OS X系统就自带鼠标所在点颜色RGB值查看工具:数码测色计,只是藏得比较深罢了。打开Finder(Dock栏第一个笑脸图标),选择应用程序--实用工具--数码测色计,双击即可启动。

        这个界面大家都能看懂了吧,中间是预览鼠标所处位置得像素,右侧显示颜色RGB值,取点范围大小可以通过滑动条来调节。

        在数码测色计得下拉菜单里选择RGB数值模式,有“255,255,255”那种,也有“0000FF”那种。

    OK,说完了,很简洁的一个苹果Mac OS X系统自带工具,但很有用。嫌它“埋”得太深,可以直接拖到上级得“应用程序”目录里(Mac的精华就是“想拖就拖”)。Enjoy your Mac

13 【Rect】CGRect比较函数

CGRectEqualToRect(tableRect, _flagshipStoreTableView.frame)


14  iOS将View的内容转变为Image

iOS将View的内容转变为Image

http://blog.sina.com.cn/s/blog_9c3c519b01014g73.html


15 UITableview最后一行显示不全

    //tableview的高度减去tabbar的高度就好了

    float screenHeight = [[UIScreen mainScreen] applicationFrame].size.height;

    float scale = [[UIScreen mainScreen] scale];

    float statusHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;

    float navHeight = self.navigationController.view.frame.size.height;

    float navBarHeight = self.navigationController.navigationBar.frame.size.height;

    float tabBarHeight = self.navigationController.tabBarController.tabBar.frame.size.height;

    float toolBarHeight = self.navigationController.toolbar.frame.size.height;

    float contentViewHeight = navHeight - statusHeight - navBarHeight -tabBarHeight;

    LOGDEBUG([NSString stringWithFormat:@"screenHeight:%f, navH:%f, navBarH:%f, tabBarH:%f, toolBarH:%f, contentViewHeight:%f", screenHeight, navHeight, navBarHeight, tabBarHeight, toolBarHeight, contentViewHeight]);

    // [_flagshipStoreInfoView setFrame:CGRectMake(0, self.mapView.frame.origin.y + self.mapView.frame.size.height, self.view.frame.size.width, contentViewHeight - self.mapView.frame.size.height)];


16 转换NSString为UTF8编码的函数

 - (NSString*)URLEncodedString{  

    NSString *result = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);

   [resultautorelease];

   returnresult;

}

 - (NSString*)URLDecodedString{

   NSString*result = (NSString*) CFURLCreateStringByReplacingPercentEscapesUsingEncoding (kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8);

   [resultautorelease];

   returnresult;

}

http://blog.csdn.net/zaitianaoxiang/article/details/6651454


17 【NSURL】NSURL各参数

//测试url

NSURL *url = [NSURL URLWithString: @"http://www.baidu.com/s?tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709"];

  NSLog(@"Scheme: %@", [url scheme]);

  NSLog(@"Host: %@", [url host]);

  NSLog(@"Port: %@", [url port]);

  NSLog(@"Path: %@", [url path]);

  NSLog(@"Relative path: %@", [url relativePath]);

  NSLog(@"Path components as array: %@", [url pathComponents]);

  NSLog(@"Parameter string: %@", [url parameterString]);

  NSLog(@"Query: %@", [url query]);

  NSLog(@"Fragment: %@", [url fragment]);

  NSLog(@"User: %@", [url user]);

  NSLog(@"Password: %@", [url password]);

显示如下:

2012-01-10 13:46:01.528 Letter[1758:10d03] Scheme: http

2012-01-10 13:46:01.686 Letter[1758:10d03] Host: www.cocoachina.com

2012-01-10 13:46:01.840 Letter[1758:10d03] Port: (null)

2012-01-10 13:46:01.986 Letter[1758:10d03] Path: /bbs/read.php

2012-01-10 13:46:02.170 Letter[1758:10d03] Relative path: /bbs/read.php

2012-01-10 13:46:02.324 Letter[1758:10d03] Path components as array: ( "/", bbs, "read.php")

2012-01-10 13:46:02.492 Letter[1758:10d03] Parameter string: (null)

2012-01-10 13:46:02.715 Letter[1758:10d03] Query: tid-70265.html

2012-01-10 13:46:02.863 Letter[1758:10d03] Fragment: (null)

2012-01-10 13:46:03.056 Letter[1758:10d03] User: (null)

2012-01-10 13:46:03.427 Letter[1758:10d03] Password: (null)

http://blog.sina.com.cn/s/blog_45e2b66c01010dm0.html


18 【UI】键盘消失的方法

触摸非输入区(背景)使UITextField(UISearchBar)键盘消失的方法

http://blog.sina.com.cn/s/blog_a7c44c8801018c33.html

- (void)resignKeyBoardInView:(UIView *)view

{

    for (UIView *v inview.subviews) {

        if([v.subviews count] > 0) {

            [selfresignKeyBoardInView:v];

        }

        if ([visKindOfClass:[UITextView class]] || [v isKindOfClass:[UITextField class]]) {

            [v resignFirstResponder];

        }

    }

}


19 【UI】UIActivityIndicatorView的使用(菊花)

iOS UIActivityIndicatorView的使用(菊花)

http://blog.csdn.net/zhaopenghhhhhh/article/details/12092657

UIActivityIndicatorView非常简单 ,就是一个转圈圈的控件

初始化方法

- initWithActivityIndicatorStyle

控制一个Activity Indicator

- startAnimating

- stopAnimating

- isAnimating

hidesWhenStopped属性

配置Activity Indicator外观

activityIndicatorViewStyle属性

color属性  (iOS 5  引入)


常量三个

typedef enum { 

    UIActivityIndicatorViewStyleWhiteLarge, 

    UIActivityIndicatorViewStyleWhite, 

    UIActivityIndicatorViewStyleGray,

} UIActivityIndicatorViewStyle; 


使用方式就是

UIActivityIndicatorView *testActivityIndicator =

[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite]];

testActivityIndicator.center = CGPointMake(100.0f,100.0f);//只能设置中心,不能设置大小

[testActivityIndicator setFrame = CGRectMack(100, 100,100, 100)];//不建议这样设置,因为UIActivityIndicatorView是不能改变大小只能改变位置,这样设置得到的结果是控件的中心在(100,100)上,而不是和其他控件的frame一样左上角在(100,100)长为100,宽为100.

[self addSubview:testActivityIndicator];

testActivityIndicator.color = [UIColor redColor]; //改变圈圈的颜色为红色;iOS5引入

[testActivityIndicator startAnimating]; //开始旋转

[testActivityIndicator stopAnimating]; //结束旋转

[testActivityIndicator setHidesWhenStopped:YES];//当旋转结束时隐藏

        还有一个是isAnimating方法,返回一个BOOL值,可以用这个方法来判断控件是否在旋转

        initWithActivityIndicatorStyle是UIActivityIndicatorView唯一的初始化方法

        属性值是一个枚举变量,只有三个值:

    UIActivityIndicatorViewStyleWhite;白色圆圈

    UIActivityIndicatorViewStyleWhiteLarge;白色圆圈但是要大些

    UIActivityIndicatorViewStyleGray;灰色圆圈

IOS风火轮、菊花、loading使用

http://my.oschina.net/wangdk/blog/152730


20 【逻辑】NSData,NSImage,NSDictionary,NSString,NSInteger,Float,NSURL等等互相转换

NSData转NSDictionary

-(NSMutableDictionary *) getCityInfoDicWithData:(NSData*) cityInfo

{

    if(cityInfo) {

        //  NSDictionary * tempDic =[NSJSONSerialization JSONObjectWithData: cityInfo options:  NSJSONReadingMutableContainers error: nil];

        NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:cityInfo];

        NSDictionary*tempDic = [unarchiver decodeObjectForKey:_provinceEntity.name];

        [unarchiverfinish Decoding];


        if(!tempDic) {

            return nil;

        }


        NSMutableDictionary *dic =[[NSMutableDictionary alloc] initWithDictionary: tempDiccopyItems: YES];

        returndic;

    }

    else return [[NSMutableDictionary alloc] init];

}


NSDictionary转 NSData

-(BOOL)saveEntity

{

    NSMutableData*data = [[NSMutableData alloc] init];

    NSKeyedArchiver*archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiverencodeObject:self.cityInfoDic forKey:self.provinceEntity.name];

    [archiverfinish Encoding];

    self.provinceEntity.cityInfo=data;

    return YES;

}

NSData,NSImage,NSDictionary,NSString,NSInteger,Float,NSURL等等互相转换

http://blog.163.com/moon_walker/blog/static/213179094201401524753450/

iOS NSDictionary、NSData、JSON数据类型相互转换

http://blog.csdn.net/tangwei019917/article/details/8671535


21 【UI】UIImage如何从URL加载图像?

UIImage如何从URL加载图像?

NSString *myURL = [objectobjectForKey:@"ProductImage"];

cell.imageView.image = [UIImage imageWithData:[NSDatadataWithContentsOfURL:[NSURL URLWithString:myURL]]];

你可能感兴趣的:(IOS开发问题索引(六))