IOS 冷门知识

来源:互联网 发布:哈尔滨软件培训学校 编辑:程序博客网 时间:2024/05/02 19:50

原文地址: http://blog.sina.com.cn/s/blog_801997310101cthq.html  支持原创

1.刷新单个tableviewcell

       NSIndexPath * indexPat=[NSIndexPath indexPathForRow:indexPlay inSection:0];

        NSArray * indexArray=[NSArray arrayWithObject:indexPat];

        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];

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

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

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

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

    return anInt -1;

};

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


4.  改变buuton的高亮

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

    iv.userInteractionEnabled = YES;

    UIButton * navBtn = [UIButton buttonWithType:UIButtonTypeCustom];

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

    [navBtn setImage:[UIImage imageNamed:@"rong_Tian"] forState:UIControlStateNormal];

    [navBtn setHighlighted:YES];

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

    [navBtn setShowsTouchWhenHighlighted:YES];

    [iv addSubview:navBtn];

    [self.navigationController.navigationBar addSubview:iv];

5. 默认为cell第一行

 

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

    [self.tableView selectRowAtIndexPath:first animated:YES scrollPosition: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=[NSURL URLWithString:str];

//    

//      NSURLRequest *requestt = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

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

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

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


7.距离感应器

UIDeviceOrientation orientation3=  [[UIDevice currentDevice] orientation];

 

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

    [[UIDevice currentDevice] 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 to user");    

        }   

    }

8.获得cookie

 

    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

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

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

    }

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

 

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary] == YES)

    {

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

        videoLibraryController.delegate = self;

        videoLibraryController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

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

        [videoLibraryController setAllowsEditing:YES];

        [self.navigationController presentViewController:videoLibraryController animated:YES completion:^{

            

        }];

    }

    else

    {

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

    }


 10. 读取全局的Delegate:
KiloNetAppDelegate *appdelegate = (KiloNetAppDelegate *)[[UIApplication sharedApplication] 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 = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];

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

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


[dictplist setObject:self.strWeb_id forKey:@"web_id"];

        [dictplist writeToFile:plistPath atomically:YES];

15.获取文件夹的大小

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

    NSFileManager* manager = [NSFileManager defaultManager];

    if ([manager fileExistsAtPath:filePath]){

        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

    }

    return 0;

}

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.0f alpha:1.0f];

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

 

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

    [self performSelector:@selector(deselect) withObject:nil afterDelay:0.5f];

- (void)deselect

{

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

}

17.改变UITableViewStyleGrouped背景颜色

 

self.tableVieww.backgroundColor =[UIColor colorWithPatternImage:[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 already includes gloss effects  设置为YES              也就是用自己的icon,不用系统的了

20.动态UIlable后添加图片

    self.userNameLabel=[[[UILabel alloc]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];

    CGSize size = [self.strNamee sizeWithFont:font constrainedToSize:CGSizeMake(277, 20.0f)];

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

    CGRect rect=self.userNameLabel.frame;

    rect.size=size;

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

    [self.userNameLabel setFrame:rect];


//判断男女

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

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

//时间差

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

{

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

    [date setDateFormat:@"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 = [NSString stringWithFormat:@"%f", cha/60];

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

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

        

    }

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

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

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

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

    }

    if (cha/86400>1)

    {

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

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

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

        

    }

    [date release];

    return timeString;

}

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

在cell.contentView上: 

//获得row

NSInteger row = [[self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]] row];

//获得section

NSInteger row = [[self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]] section];

//获得indexPath

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

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

 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@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
  Referenced from: /Users/⋯⋯/Application Support/iPhone Simulator/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:NO withAnimation: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 = [NSDictionary dictionaryWithObject:[NSNumbernumberWithBool: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(1030300    , 225);

    player.contentURL = url;

    player.repeatMode = MPMovieRepeatModeOne;  

    player.controlStyle = MPMovieControlStyleEmbedded;

 

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

    [self.view addSubview:player.view];

    [player play];

(2).avplayer

 


[[NSNotificationCenter defaultCenteraddObserver:self selector:@selector(playerItemDidReachEnd:)                                                       name:AVPlayerItemDidPlayToEndTimeNotification

                                                                                            object:plaitem];

                                              }

                                          }];


   #pragma mark - 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 allocinit];

     long size = 0;

    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];

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

    {

        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];

       

        BOOL isDir;

        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )

        {

            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];

            size+= fileAttributeDic.fileSize;

        }        else        {

            [self fileSizeForDir:fullPath];

        }

    }

    [fileManager release];    return size;    }

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=[[NSThread alloc]initWithTarget:self selector:@selector(thAction) object:nil];

//    [th start];

    

//[NSThread detachNewThreadSelector:@selector(thAction) toTarget:self withObject:nil];

   

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

   

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

//    [operationQueue addOperationWithBlock:^{

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

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

//        }

//    }];

   

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

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

//    operationQueue.maxConcurrentOperationCount=1;

//    

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

//    [invocation1 setQueuePriority:NSOperationQueuePriorityLow];

//    

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

//    [invocation2 setQueuePriority:NSOperationQueuePriorityHigh];

//    [operationQueue addOperation:invocation1];

 

//    [operationQueue addOperation:invocation2];

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

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

- (void)mutiThread

{

    NSLog(@"Start NStimer");

    @autoreleasepool {

        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nilrepeats:YES];

    }

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

    [[NSRunLoop currentRunLoop]run];

    NSLog(@"after");

}

- (void)timerAction:(NSTimer * )timer

{

    i++;

    NSLog(@"Print NSTimer");

    if (i==5) {

        [timer invalidate];

    }

}

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

 if (self.presentingViewController) {

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

34。等比例放大缩小视图

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

    [UIView animateWithDuration:.5 animations:^{

        CGAffineTransform transform=la.transform;

        transform=CGAffineTransformScale(la.transform1.51.5);

        la.transform=transform;

    } completion:^(BOOL finished) {

        CGAffineTransform transform=la.transform;

        transform=CGAffineTransformScale(la.transform0.50.5);

        la.transform=transform;

    }];

35.清掉编译文件

~/Library/Developer/Xcode/DerivedData

模拟器清空编译

~/Library/Application Support/iPhone Simulator/

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

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

    [[UIApplication sharedApplication] 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.new removeItemAtPath:outputURL error:nil];

            [NSFileManager.new createDirectoryAtPath:outputURL

                         withIntermediateDirectories:YES

                                          attributes:nil

                                               error:NULL];

39. 在document下创建文件 

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

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

    [[NSFileManager defaultManager] createFileAtPath:writePath contents:data attributes: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 *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

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

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    

    RootViewController *rooViewController = [[RootViewController alloc]init];

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

    

    

    self.window.rootViewController = navgationVC;

    

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

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

    [self.window addSubview:splashView];

    [self.window bringSubviewToFront:splashView];

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:2.0];

    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView: self.window cache:YES];

    [UIView setAnimationDelegate:self];

    [UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:context:)];

    splashView.alpha = 0.0;

    splashView.frame = CGRectMake(-60, -85440635);

    [UIView commitAnimations];

    

    

    [self.window makeKeyAndVisible];

    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 plaincopy
    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 plaincopy
    1. [[UIApplication sharedApplication] setIdleTimerDisabled:YES];  

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

    NSArray *viewControllers = [self.navigationController viewControllers];

    UIViewController *viewControll = [viewControllers objectAtIndex:2];

      [self.navigationController pushViewController:viewControll animated:YES];

58,图片模糊化处理

 


[cpp] view plaincopy
  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 }); // 一次性执行: staticdispatch_once_t onceToken; dispatch_once(&onceToken,^{ // code to be executed once }); // 延迟2秒执行: doubledelayInSeconds = 2.0; dispatch_time_tpopTime = 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)UIBackgroundTaskIdentifierbackgroundUpdateTask; // 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 0