您的位置:首页 > 移动开发 > IOS开发

iOS开发经常用到的技术知识点

2013-10-09 16:21 417 查看
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=ASIHTTPRequestErrorDomain Code=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







把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:***URLAssetPreferPreciseDurationAndTimingKey];

***URLAsset *urlAsset = [***URLAsset 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



[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:***PlayerItemDidPlayToEndTimeNotification

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 alloc] init];

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. 谓词过滤

//搜索用谓词过滤数组

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:nil repeats: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.transform, 1.5, 1.5);

la.transform=transform;

} completion:^(BOOL finished) {

CGAffineTransform transform=la.transform;

transform=CGAffineTransformScale(la.transform, 0.5, 0.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)<%an>%Creset' --abbrev-commit --"
$ git lg

52.查看远程 git

git remote show origin

53.显示远程git仓库

git remote show

54.OC冒泡排序

//   NSMutableArray 自带排序方法

  NSMutableArray *lastArrary = [NSMutableArray arrayWithArray:sinceArray];

    [lastArrary sortedArrayUsingSelector:@selector(compare:)];

- (NSComparisonResult)compare:(NSNumber *)otherNumber

{

  // 设置升  降序
    return NSOrderedDescending;

}

// 冒泡排序
NSMutableArray *sinM_Array = [NSMutableArray arrayWithArray:sinceArray];

    for (int x = 0; x < sinceArray.count -1; x ++) {

        for (int y = x + 1; y < sinceArray.count - 1 -x; y ++) {

                int leftNum = [[sinM_Array objectAtIndex:x] intValue];

                int rightNum = [[sinM_Array objectAtIndex:y]intValue];

            if (leftNum > rightNum) {

                [sinM_Array replaceObjectAtIndex:x withObject:[NSNumber numberWithInt:leftNum]];

                [sinM_Array replaceObjectAtIndex:y withObject:[NSNumber numberWithInt:rightNum]];

            }

        }

    }

55.前后摄像头的切换

- (***CaptureDevice *)cameraWithPosition:(***CaptureDevicePosition)position

{

    NSArray *devices = [***CaptureDevice devicesWithMediaType:***MediaTypeVideo];

    for ( ***CaptureDevice *device in devices )

        if ( device.position == position )

            return device;

    return nil;

}

- (void)backCarme:(UIButton *)button

{

    NSArray *inputs = self.session.inputs;

    for ( ***CaptureDeviceInput *input in inputs ) {

        ***CaptureDevice *device = input.device;

        if ( [device hasMediaType:***MediaTypeVideo] ) {

            ***CaptureDevicePosition position = device.position;

            ***CaptureDevice *newCamera = nil;

            ***CaptureDeviceInput *newInput = nil;

            if (position == ***CaptureDevicePositionFront)

                newCamera = [self cameraWithPosition:***CaptureDevicePositionBack];

            else

                newCamera = [self cameraWithPosition:***CaptureDevicePositionFront];

            newInput = [***CaptureDeviceInput deviceInputWithDevice:newCamera error:nil];

            [self.session beginConfiguration];

            [self.session removeInput:input];

            [self.session addInput:newInput];

            [self.session commitConfiguration];

            break;

        }

    }  

}

56.#pragma mark --获得视频的尺寸


-(CGSize)getImage:(NSURL *)url

{

NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]forKey:***URLAssetPreferPreciseDurationAndTimingKey];

***URLAsset *urlAsset = [***URLAsset URLAssetWithURL:url options:opts];

CGSize size = [[[urlAsset tracksWithMediaType:***MediaTypeVideo] objectAtIndex:0] naturalSize];

return size;

}

57.播放音频

// 导入框架 AudioToolbox.framework

NSString *path = [[NSBundle mainBundle] pathForResource:@"msgcome" ofType:@"wav"];

NSURL *url = [NSURL fileURLWithPath:path];

SystemSoundID soundId;

AudioServicesCreateSystemSoundID((CFURLRef)url,
&soundId);

AudioServicesPlaySystemSound(soundId);

原文地址:http://blog.sina.com.cn/s/blog_801997310101cthq.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: