常见项目技术点汇总

1.刷新单个tableviewcell

      NSIndexPath* indexPat=[NSIndexPath indexPathForRow:indexPlayinSection:0];

       NSArray * indexArray=[NSArrayarrayWithObject:indexPat];

       [self.tableViewreloadRowsAtIndexPaths:indexArraywithRowAnimation:UITableViewRowAnimationAutomatic];

2.  判断该方法是否执行??

BOOL isss= [cell.queuePlayerrespondsToSelector:@selector(play)];

instancesRespondToSelector是指类的实例们是否能响应某一个方法(类操作),respondsToSelector是指类是否能响应某一方法(对象)
3.代码块的使用

int (^oneFrom)(int) = ^(int anInt){

    returnanInt -1;

};

   NSLog(@"%d",oneFrom(10));


4. 改变buuton的高亮

UIImageView * iv = [[UIImageViewalloc] initWithFrame:CGRectMake(250, 5, 50, 34)];

   iv.userInteractionEnabled = YES;

   UIButton * navBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];

   navBtn.frame = CGRectMake(0, 0, 50,34);

   [navBtn setImage:[UIImageimageNamed:@"rong_Tian"] forState:UIControlStateNormal];

   [navBtn setHighlighted:YES];

   [navBtn addTarget:selfaction:@selector(btnPressed:)forControlEvents:UIControlEventTouchUpInside];

   [navBtnsetShowsTouchWhenHighlighted:YES];

   [iv addSubview:navBtn];

   [self.navigationController.navigationBaraddSubview:iv];

5.默认为cell第一行

 

 NSIndexPath *first=[NSIndexPathindexPathForRow:0 inSection:0];

    [self.tableViewselectRowAtIndexPath:first animated:YESscrollPosition:UITableViewScrollPositionBottom];


6.一个项目中  ARC和非ARC的混合使用

     

点击项目--》TARGETS-》Build Phases  -》Compile Sources   中选择要改的.m  双击   在标签中写:

1.如果是ARC项目,要加入非ARC的代码文件  fobjc-arc

2.如果是非ARC,要加入ARC的代码  -fno-objc-arc     Enter就OK


 

//    NSURL * url=[NSURLURLWithString:str];

//    

//     NSURLRequest *requestt = [[NSURLRequest alloc]initWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:10];

//     NSData *received =[NSURLConnection sendSynchronousRequest:requesttreturningResponse:nil error:nil];

//    NSString *strr = [[NSStringalloc]initWithData:received encoding:NSUTF8StringEncoding];

//    NSLog(@"这是 成功返回的信息    %@",strr);


7.距离感应器

UIDeviceOrientationorientation3=  [[UIDevicecurrentDevice]orientation];

 

   NSLog(@"获取当前状态  %d",orientation3);

    [[UIDevicecurrentDevice]setProximityMonitoringEnabled:YES];

   [[NSNotificationCenter defaultCenter]addObserver:self 

                                     selector:@selector(sensorStateChange:)

                               name:@"UIDeviceProximityStateDidChangeNotification"

    

                                       object:nil];

 -(void)sensorStateChange:(NSNotificationCenter*)notification;

   { 

       if ([[UIDevice currentDevice]proximityState] == YES) {

          

          NSLog(@"Device is close to user");

          //在此写接近时,要做的操作逻辑代码  

       }else{

          NSLog(@"Device is not close touser");   

       }  

   }

8.获得cookie

 

   NSHTTPCookieStorage *cookieJar= [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for(NSHTTPCookie *cookie in [cookieJar cookies]) {

       NSLog(@"cookie=====    %@", cookie);

   }

9.从相册中只获得视频文件

 

if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]== YES)

   {

       UIImagePickerController*videoLibraryController = [[[UIImagePickerController alloc] init]autorelease];

      videoLibraryController.delegate = self;

      videoLibraryController.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

      videoLibraryController.mediaTypes = [NSArrayarrayWithObject:(NSString *)kUTTypeMovie];

       [videoLibraryControllersetAllowsEditing:YES];

       [self.navigationControllerpresentViewController:videoLibraryController animated:YEScompletion:^{

          

       }];

   }

   else

   {

       [selfAlertlogError:@"暂时你还没有视频"];

   }


 10.读取全局的Delegate:
KiloNetAppDelegate*appdelegate = (KiloNetAppDelegate *)[[UIApplicationsharedApplication] delegate];

11.键盘透明

textField.keyboardAppearance= UIKeyboardAppearanceAlert;
12.URL错误:

Error Domain=ASIHTTPRequestErrorDomaiCode=5 "Unable to create request (bad url?)" UserInfo=0x69ba0f0 {NSLocalizedDescription=Unable to create request (bad url?)}

解决办法:

NSString*url =@"http://oerp.xixingsoft.com:8083/oadata/MobileConfig.nsf/GetStandList?openagent&ViewNumber=新闻中心";

        url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        

        NSStringEncodingenc CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);//gbk code-->utf8 code

        NSData*data [url dataUsingEncoding:NSUTF8StringEncoding];//[request responseData];

        NSString*utf8str [[[NSStringalloc] initWithData:data encoding:enc] autorelease]; 

13.请求中加cookie、 heard

当你需要添加更多的请求信息时,如,添加个请求Header:
[request addRequestHeader:@"name" value:@"Jory lee"];

14 Plist文件的保存 修改   除非在decument是可读可写的(在工程中 可读不可写)

    //获取路径对象

    NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

   //获取完整路径

   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *plistPath = [documentsDirectorystringByAppendingPathComponent:@"test.plist"];

   NSLog(@"plist  地质  %@",plistPath);

   NSMutableDictionary *dictplist = [[NSMutableDictionary alloc ]init];


[dictplist setObject:self.strWeb_idforKey:@"web_id"];

       [dictplistwriteToFile:plistPath atomically:YES];

15.获取文件夹的大小

-(long long) fileSizeAtPath:(NSString*)filePath{

   NSFileManager* manager = [NSFileManager defaultManager];

    if([manager fileExistsAtPath:filePath]){

       return [[managerattributesOfItemAtPath:filePath error:nil] fileSize];

   }

    return0;

}

16.改变tablevlewcell点击的颜色

 

cell.selectedBackgroundView = [[[UIView alloc]initWithFrame:cell.frame] autorelease];

   cell.selectedBackgroundView.backgroundColor =[UIColor colorWithRed:54/255.0f green:110/255.0f blue:100/255.0falpha:1.0f];

cell.textLabel.highlightedTextColor [UIColor xxxcolor];  [cell.textLabel setTextColor:color

 

点击后,过段时间cell自动取消选中

   [selfperformSelector:@selector(deselect) withObject:nilafterDelay:0.5f];

- (void)deselect

{

   [self.tableVieww deselectRowAtIndexPath:[self.tableViewwindexPathForSelectedRow] animated:YES];

}

17.改变UITableViewStyleGrouped背景颜色

 

self.tableVieww.backgroundColor =[UIColorcolorWithPatternImage:[UIImage imageNamed:@"更多背景图.png"]];

   self.tableVieww.backgroundView =nil;

18.视图反转

 //水平
    queuePlayer.transform= CGAffineTransformScale(queuePlayer.transform,1.0, -1.0);

//垂直    queuePlayer.transform= CGAffineTransformScale(queuePlayer.transform,-1.0, 1.0);
19.改变icon的阴影圆圈,取消图标上的高光

   1.进入plist文件   2.在Supported interface orientations 添加 Icon alreadyincludes gloss effects 设置为YES           也就是用自己的icon,不用系统的了

20.动态UIlable后添加图片

   self.userNameLabel=[[[UILabelalloc]initWithFrame:CGRectMake(60, 7, 220,20)]autorelease];

   self.userNameLabel.textColor= [UIColor blackColor];

   self.userNameLabel.text=self.strNamee;

   self.userNameLabel.backgroundColor=[UIColor clearColor];

   self.userNameLabel.numberOfLines=0;

    UIFont*font = [UIFont fontWithName:@"Helvetica-Bold"size:17.0f];

   [self.userNameLabel setFont:font];

   [self.contentView addSubview:self.userNameLabel];

    CGSizesize = [self.strNamee sizeWithFont:fontconstrainedToSize:CGSizeMake(277, 20.0f)];

   NSLog(@"kuang %f  ",size.width);

    CGRectrect=self.userNameLabel.frame;

   rect.size=size;

   NSLog(@"321   %f   %f",rect.size.width,rect.size.height);

   [self.userNameLabel setFrame:rect];


//判断男女

   UIImageView * imaSex=[[UIImageViewalloc]initWithFrame:CGRectMake(self.userNameLabel.frame.size.width+65,10, 12, 13)];

21.向自定义的cell中传值,最好用 方法在tableview中来调用 如果有参数 直接来传
22.精确时间差

//时间差

- (NSString *)intervalSinceNow: (NSString *)theDate

{

   NSDateFormatter *date=[[NSDateFormatter alloc] init];

    [datesetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate*d=[date dateFromString:theDate];

   NSTimeInterval late=[d timeIntervalSince1970]*1;

    NSDate*dat = [NSDate dateWithTimeIntervalSinceNow:0];

   NSTimeInterval now=[dat timeIntervalSince1970]*1;

   NSString *timeString=@"";

   NSTimeInterval cha=now-late;

    if(cha/3600<1) {

       timeString = [NSStringstringWithFormat:@"%f", cha/60];

       timeString = [timeStringsubstringToIndex:timeString.length-7];

       timeString=[NSStringstringWithFormat:@"%@分钟前",timeString];

       

   }

    if(cha/3600>1&&cha/86400<1) {

       timeString = [NSStringstringWithFormat:@"%f", cha/3600];

       timeString = [timeStringsubstringToIndex:timeString.length-7];

       timeString=[NSStringstringWithFormat:@"%@小时前",timeString];

   }

    if(cha/86400>1)

   {

       timeString = [NSStringstringWithFormat:@"%f", cha/86400];

       timeString = [timeStringsubstringToIndex:timeString.length-7];

       timeString=[NSStringstringWithFormat:@"%@天前",timeString];

       

   }

    [daterelease];

    returntimeString;

}

22.按钮在cell上单击第几行

在cell.contentView上: 

//获得row

NSIntegerrow = [[self.tableView indexPathForCell:(UITableViewCell *)[[sendersuperview] superview]] row];

//获得section

NSIntegerrow = [[self.tableView indexPathForCell:(UITableViewCell *)[[sendersuperview] superview]] section];

//获得indexPath

NSIndexPath*indexPath = [self.tableView indexPathForCell:(UITableViewCell*)[[sender superview] superview]];

直接添加到cell上
//获得row
NSInteger row =[[self.tableView indexPathForCell:(UITableViewCell *)[sendersuperview]] row];
//获得section
NSInteger section =[[self.tableView indexPathForCell:(UITableViewCell *)[sendersuperview]] section];
//获得indexPath
NSIndexPath *indexPath =[self.tableView indexPathForCell:(UITableViewCell *)[sendersuperview]];
23:判断Home键在哪个方法要执行对应的方法

 [[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];

   [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(rongTianOrientation:)name:@"UIDeviceOrientationDidChangeNotification"object:nil];

 

-(void) deviceOrientationDidChangeAction:(NSNotification*)note

{

    NSInteger currentOrientation =[[note object] orientation];

    switch (currentOrientation) {

          case0: {  //未知方向

               break;

          }

          case1: {  //home键向下

              break;

         }

          case2: {  //home键向上

              break;

          }

          case3:{  //home键向左

               break;

          }

          case4:{  //home键向右

               break;

          }

         default:

              break;

   }

}

24.模拟器不能运行的错误 

dyld: Library not loaded:@rpath/SenTestingKit.framework/Versi*****/A/SenTestingKit
  Referencedfrom: /Users/⋯⋯/Application Support/iPhoneSimulator/5.0/Applicati*****/F179924C-0EB7-4CCA-88D6-3BA1F68F122D/ILUTU.app/ILUTU
  Reason:image not found

 

iOS <wbr>第6项目个别技术点

把SentestingKit。frameWork 有原来的required改为Optional 就ok

25.还原状态栏

显示原来的状态栏

  (1)

  [[UIApplication sharedApplication] setStatusBarHidden:NOwithAnimation:YES];

   [[UIApplication sharedApplication].keyWindow setFrame:CGRectMake(0,20, 320,[UIScreen mainScreen].applicationFrame.size.height)];

 

//重新设定标题栏显示的位置

   [self.navigationController.navigationBar setFrame:CGRectMake(0,0, 320,44)];

(2)

在别的页面[[UIApplication sharedApplication].keyWindow setFrame:CGRectMake(0, 0, 320,[UIScreenmainScreen].applicationFrame.size.height)];

26.获得相册视频的总时间

-(int)getVideopTime:(NSURL* )videourl

{

   NSDictionary *opts = [NSDictionarydictionaryWithObject:[NSNumber numberWithBool:NO]

                                            forKey:AVURLAssetPreferPreciseDurationAndTimingKey];

    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:videourl options:opts]; // 初始化视频媒体文件

    int minute = 0, second = 0;

    second =urlAsset.duration.value / urlAsset.duration.timescale; // 获取视频总时长,单位秒

   NSLog(@"movie duration : %d", second);

    if (second >= 60) {

       int index =second / 60;

       minute = index;

       second = second - index*60;

    }

    return second;

}

27.视频播放器 循环播放 大小……

  (1) MPMoviePlayerController

  MPMoviePlayerController*player;

   NSURL *url =[NSURL URLWithString:fileName];

    player =[[MPMoviePlayerController alloc]init];

   player.view.frame = CGRectMake(10, 30,300   , 225);

   player.contentURL = url;

   player.repeatMode=MPMovieRepeatModeOne

   player.controlStyle=MPMovieControlStyleEmbedded;

 

   player.scalingMode = MPMovieScalingModeAspectFill;   //充满屏幕

   [self.view addSubview:player.view];

   [player play];

(2).avplayer

 


[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:)                                              name:AVPlayerItemDidPlayToEndTimeNotification

                                                                              object:plaitem];

                                       }

                                    }];


  #pragmamark - Notification Callbacks

-(void)playerItemDidReachEnd:(NSNotification *)notification {

   NSLog(@"是跳转第一侦吗? ");

   [self.queuePlayer seekToTime:kCMTimeZero];

   [self.queuePlayer play];

}

28.sina微博错误返回值格式

http://open.weibo.com/wiki/Error_code

29.ios 获得文件夹的大小

 

//计算文件夹下文件的总大小

-(long)fileSizeForDir:(NSString*)path

{

   NSFileManager *fileManager =[[NSFileManager alloc]init];

    long size =0;

   NSArray* array = [fileManagercontentsOfDirectoryAtPath:patherror:nil];

   for(int i =0; i<[array count]; i++)

   {

      NSString *fullPath = [pathstringByAppendingPathComponent:[arrayobjectAtIndex:i]];

      

      BOOL isDir;

      if ( !([fileManagerfileExistsAtPath:fullPathisDirectory:&isDir] && isDir) )

      {

          NSDictionary*fileAttributeDic=[fileManagerattributesOfItemAtPath:fullPatherror:nil];

          size+=fileAttributeDic.fileSize;

      }      else      {

          [selffileSizeForDir:fullPath];

      }

   }

   [fileManager release];   returnsize;   }

30. iOS  谓词过滤 (ios谓词)

//搜索用谓词过滤数组

   NSArray *arrMy=@[@"2荣三a",@"李四b",@"王五a",@"李流j",@"荣天321",@"iOS基地",@"iOS7"];

    NSString  *strg=@"";

    NSPredicate * fiecate=[NSPredicate predicateWithFormat:@"SELF CONTAINS %@",strg];

    NSArray * arr3=[arrMy filteredArrayUsingPredicate:fiecate];

   NSLog(@"这是我过滤的数组对吗?%@",arr3);

31.多线程的多种创建

  

//   NSThread * th=[[NSThreadalloc]initWithTarget:self selector:@selector(thAction)object:nil];

//   [th start];

   

//[NSThreaddetachNewThreadSelector:@selector(thAction) toTarget:selfwithObject:nil];

  

  // [self performSelectorInBackground:@selector(thAction)withObject:self];

  

//   NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];

//   [operationQueueaddOperationWithBlock:^{

//       for(inti=0; i<20;i++){

//          NSLog(@"This isThread:%d",i);

//      }

//   }];

  

//   NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];

//   //设置线程池中的并发数

//  operationQueue.maxConcurrentOperationCount=1;

//   

//   NSInvocationOperation *invocation1=[[NSInvocationOperation alloc]initWithTarget:selfselector:@selector(threadOne) object:nil];

//   [invocation1setQueuePriority:NSOperationQueuePriorityLow];

//   

//   NSInvocationOperation *invocation2=[[NSInvocationOperation alloc]initWithTarget:selfselector:@selector(threadTwo) object:nil];

//   [invocation2setQueuePriority:NSOperationQueuePriorityHigh];

//   [operationQueueaddOperation:invocation1];

 

//    [operationQueueaddOperation:invocation2];

32.用多线程开启Nstimer提高精确度

//用多线程开启nstimer提高精确度

-(void)mutiThread

{

   NSLog(@"StartNStimer");

   @autoreleasepool{

      [NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(timerAction:)userInfo:nilrepeats:YES];

   }

  //获得当前的runloop,线程就停在这里

   [[NSRunLoopcurrentRunLoop]run];

  NSLog(@"after");

}

-(void)timerAction:(NSTimer *)timer

{

   i++;

   NSLog(@"PrintNSTimer");

   if (i==5){

       [timerinvalidate];

   }

}

33.判断此页面是push,还是模态过来的

 if(self.presentingViewController){

       NSLog(@"这个是模态过来的!");}

34。等比例放大缩小视图

  UILabel *la=(UILabel * )[self.viewviewWithTag:908];

   [UIViewanimateWithDuration:.5animations:^{

       CGAffineTransformtransform=la.transform;

      transform=CGAffineTransformScale(la.transform,1.5, 1.5);

       la.transform=transform;

    }completion:^(BOOL finished) {

       CGAffineTransformtransform=la.transform;

      transform=CGAffineTransformScale(la.transform,0.5, 0.5);

       la.transform=transform;

    }];

35.清掉编译文件

~/Library/Developer/Xcode/DerivedData

模拟器清空编译

~/Library/Application Support/iPhone Simulator/

36.改变状态栏的颜色状态

   [[UIApplicationsharedApplication]setStatusBarStyle:UIStatusBarStyleDefault];

   [[UIApplicationsharedApplication]setStatusBarHidden:NO];

37.给自己的项目中添加特殊的标示符号

http://patorjk.com/software/taag/#p=moreopts&h=0&v=1&f=优雅&t=V

38 清空某个文件夹

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

      NSString *outputURL =paths[0];

       [NSFileManager.newremoveItemAtPath:outputURLerror:nil];

         [NSFileManager.newcreateDirectoryAtPath:outputURL

                    withIntermediateDirectories:YES

                                  attributes:nil

                                      error:NULL];

39.在document下创建文件 

 NSString*writePath=[NSStringstringWithFormat:@"%@/%@.txt",stre,@"aaa"];

   NSData *data =[@""dataUsingEncoding:NSUTF8StringEncoding];//新文件的初始数据,设为空

   [[NSFileManagerdefaultManager]createFileAtPath:writePath contents:dataattributes:nil];//创建文件的命令在这里

40.layoutSubviews在以下情况下会被调用:

1、init初始化不会触发layoutSubviews

2、addSubview会触发layoutSubviews
3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化
4、滚动一个UIScrollView会触发layoutSubviews
5、旋转Screen会触发父UIView上的layoutSubviews事件
6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件

41.苹果审核加急通道

https://developer.apple.com/appstore/contact/?topic=expedite

51 .美化配置git log

$ git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)
52. Default.png  添加动画

-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions

{

  self.window =[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];

   // Override point for customization afterapplication launch.

  self.window.backgroundColor= [UIColor whiteColor];

   

   RootViewController*rooViewController = [[RootViewControlleralloc]init];

   RTNavigationController *navgationVC= [[RTNavigationControlleralloc]initWithRootViewController:rooViewController];

   

   

  self.window.rootViewController= navgationVC;

   

   UIImageView *splashView =[[UIImageView alloc]initWithFrame:CGRectMake(0,0,320,568)];

   splashView.image =[UIImageimageNamed:@"Default.png"];

   [self.windowaddSubview:splashView];

   [self.windowbringSubviewToFront:splashView];

   [UIViewbeginAnimations:nilcontext:nil];

   [UIViewsetAnimationDuration:2.0];

   [UIViewsetAnimationTransition:UIViewAnimationTransitionNoneforView:self.windowcache:YES];

   [UIViewsetAnimationDelegate:self];

   [UIViewsetAnimationDidStopSelector:@selector(startupAnimationDone:finished:context:)];

   splashView.alpha =0.0;

   splashView.frame =CGRectMake(-60, -85,440, 635);

   [UIViewcommitAnimations];

   

   

  [self.windowmakeKeyAndVisible];

   return YES;

} 
53.调用系统 电话, 特定的页面

1、调用 电话phone [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://4008008288"]];
2、调用自带 浏览器 safari [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.zhece.com"]];
3、调用 自带mail [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@abt.com"]];
4、调用 SMS [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]];
5,跳转到系统设置相关界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];

其中,发短信,发Email的功能只能填写要发送的地址或号码,无法初始化发送内容,如果想实现内容的话,还需要更复杂一些,实现其各自的委托方法。
若需要传递内容可以做如下操作: 加入:MessageUI.framework   #import   实现代理:MFMessageComposeViewControllerDelegate
[java] view plaincopy
  1. 调用sendSMS函数  
  2. //内容,收件人列表  
  3. (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients  
  4.  
  5.    
  6.     MFMessageComposeViewController *controller [[[MFMessageComposeViewController alloc] init] autorelease];  
  7.    
  8.     if([MFMessageComposeViewController canSendText])  
  9.    
  10.      
  11.    
  12.         controller.body bodyOfMessage;     
  13.    
  14.         controller.recipients recipients;  
  15.    
  16.         controller.messageComposeDelegate self;  
  17.    
  18.         [self presentModalViewController:controller animated:YES];  
  19.    
  20.         
  21.    
  22.  
  23.    
  24. // 处理发送完的响应结果  
  25. (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result  
  26.  
  27.   [self dismissModalViewControllerAnimated:YES];  
  28.    
  29.   if (result == MessageComposeResultCancelled)  
  30.     NSLog(@"Message cancelled" 
  31.   else if (result == MessageComposeResultSent 
  32.     NSLog(@"Message sent"   
  33.   else   
  34.     NSLog(@"Message failed"   
  35.  
  36.    
  37.    
  38. 发送邮件的为:  
  39. 导入#import   
  40. 实现代理:MFMailComposeViewControllerDelegate  
  41.    
  42. //发送邮件  
  43. -(void)sendMail:(NSString *)subject content:(NSString *)content{  
  44.    
  45.     MFMailComposeViewController *controller [[[MFMailComposeViewController alloc] init] autorelease];  
  46.    
  47.     if([MFMailComposeViewController canSendMail])  
  48.    
  49.      
  50.    
  51.         [controller setSubject:subject];  
  52.    
  53.         [controller setMessageBody:content isHTML:NO];  
  54.    
  55.         controller.mailComposeDelegate self;  
  56.    
  57.         [self presentModalViewController:controller animated:YES];  
  58.    
  59.          
  60.  
  61.    
  62. //邮件完成处理  
  63. -(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{  
  64.    
  65.     [self dismissModalViewControllerAnimated:YES];  
  66.    
  67.     if (result == MessageComposeResultCancelled)  
  68.         NSLog(@"Message cancelled");  
  69.     else if (result == MessageComposeResultSent 
  70.         NSLog(@"Message sent");   
  71.     else   
  72.         NSLog(@"Message failed");    
  73.    
  74.  
  75.    
  76. 默认发送短信的界面为英文的,解决办法为:在.xib 中的Localization添加一組chinese

  77. 54.程序中获取软件的版本号和app名称

     

    [java]  view plain copy
    1. 应用程序的名称和版本号等信息都保存在mainBundle的infoDictionary字典中,用下面代码可以取出来。  
    2. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];  
    3. NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];//版本名称  
    4. NSString*appName =[infoDict objectForKey:@"CFBundleDisplayName"];//app名称  
    5. NSString*text =[NSString stringWithFormat:@"%@ %@",appName,versionNum]; 
      55.如何使屏幕一直保持唤醒状态?(就是不自动黑屏)[一下几条技术点 转自:路不平 博客]


    比如,如果我们做一个播放视频的功能时,想在播放的时候,不会自动进入屏保(黑屏)

    只要在代码里加入这一行:

     

    [java]  view plain copy
    1. [[UIApplication sharedApplication] setIdleTimerDisabled:YES];  

    当然,在想要黑屏的时候还需要把它设置为NO(比如视频播放完毕时),不然屏幕会在此软件运行下一直亮着。
  78. 56。如何设置视图(view)在最上层?或是view1和view2交换?
  79. self.view exchangeSubviewAtIndex:withSubviewAtIndex:];
57.返回特定的pop viewController界面

    NSArray*viewControllers =[self.navigationControllerviewControllers];

   UIViewController *viewControll = [viewControllersobjectAtIndex:2];

    [self.navigationControllerpushViewController:viewControllanimated:YES];

58,图片模糊化处理

 


[cpp]  view plain copy
  1. +(UIImage *)scale:(UIImage *)image toSize:(CGSize)size  
  2.  
  3.     UIGraphicsBeginImageContext(size);  
  4.     [image drawInRect:CGRectMake(0, 0, size.width, size.height)];  
  5.     UIImage *scaledImage UIGraphicsGetImageFromCurrentImageContext();  
  6.     UIGraphicsEndImageContext();  
  7.     return scaledImage;  
  8. }  

59.GCD的一些基本使用
// 后台执行: dispatch_async(dispatch_get_global_queue(0,0),^{ // something }); // 主线程执行: dispatch_async(dispatch_get_main_queue(),^{ // something }); // 一次性执行: static dispatch_once_t onceToken; dispatch_once(&onceToken,^{ // code to be executed once }); // 延迟2秒执行: double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime,dispatch_get_main_queue(),^(void){ // code to be executed on the main queue after delay });

60. GCD并发执行,等多个线程执行完成,再执行总线程
   dispatch_group_t grounp = dispatch_group_create ();

   dispatch_group_async(grounp,dispatch_get_global_queue(0,0), ^{

      NSLog(@" zhece.com>>>>>>>>>>>  1");

   });

  dispatch_group_async(grounp, dispatch_get_global_queue(0,0), ^{

      NSLog(@" zhece.com>>>>>>>>>>>  2");

   });

  dispatch_group_notify(grounp,dispatch_get_global_queue(0,0), ^{

      NSLog(@" zhece.com>>>>>>>>>>> 多线程完成,总执行 ");

   });

61.让程序在后台长久运行
使用block的另一个用处是可以让程序在后台较长久的运行。在以前,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是应用可以调用UIApplication的 beginBackgroundTaskWithExpirationHandler 方法,让app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作
// AppDelegate.h文件
@property(assign,nonatomic)UIBackgroundTaskIdentifier backgroundUpdateTask; // AppDelegate.m文件 - (void)applicationDidEnterBackground:(UIApplication*)application { [selfbeingBackgroundUpdateTask]; // 在这里加上你需要长久运行的代码 [selfendBackgroundUpdateTask]; } - (void)beingBackgroundUpdateTask { self.backgroundUpdateTask= [[UIApplicationsharedApplication]beginBackgroundTaskWithExpirationHandler:^{ [selfendBackgroundUpdateTask]; }]; } - (void)endBackgroundUpdateTask { [[UIApplicationsharedApplication]endBackgroundTask: self.backgroundUpdateTask]; self.backgroundUpdateTask= UIBackgroundTaskInvalid; }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值