IOS开发中有用的代码片段(持续更新)

1.NSArray中:

 

- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument;

 应用场景:在tableview中,在一个NSArray中保存了每个cell的数据下载处理对象,当数据量比较大的时候,程序可能会收到  memoryWarring,这时候,如果程序继续扩大内存使用,程序将会被操作系统“闪退”。因此在收到memoryWarring的时候需要终止或暂停所有数据下载处理对象的任务。可以使用如下代码片段:

 

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    // terminate all pending download connections
    NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
}
 

 

2.NSOperationQueue线程池:

   NSOperationQueue中添加isa NSOperation的类实例,简化了多线程程序的开发。NSOperation的子类只需要覆盖父类的main方法即可。

   a.继承NSOperation,实现自己的线程类

   //code

@interface MyTask: NSOperation

@end

@implementation MyTask
-(void)main {
//custom code
}
@end
   

   b.将MyTask子类添加到operationQueue中

     //code

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    int index = 0;
    MyTask *task1 = [[MyTask alloc] initWithTaskId:index++ andSleepTime:2.0f];
    [queue addOperation:task1];
    [task1 release];
    MyTask *task2 = [[MyTask alloc] initWithTaskId:index++ andSleepTime:2.0f];
    [queue addOperation:task2];
    [task2 release];
    
    [queue release]; 
 

   c.如果某个线程执行的任务依赖于其它线程的执行结果的时候,可以自定义线程依赖关系

    //code

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    int index = 3;
    MyTask *task3 = [[MyTask alloc] initWithTaskId:index++ andSleepTime:3.0f] ;
    [queue addOperation:task3];
    [task3 release];
    MyTask *task4 = [[MyTask alloc] initWithTaskId:index++ andSleepTime:1.0f];
    [task4 addDependency:[[queue operations] lastObject]];
    [queue addOperation:task4];
    [task4 release];
    [queue release];
 

    这样,虽然task3执行3s,task4执行1s,但是由于task4依赖于task3,因此task4在task3执行完成后才开始执行。一个     task可以设置多个这样的依赖关系。

3.去掉UISearchBar中的UISearchBarIconClear

   //code 

    for (UIView *subview in searchBar.subviews)
    {
        if ([subview conformsToProtocol:@protocol(UITextInputTraits)]) {
            [(UITextField *)subview setClearButtonMode:UITextFieldViewModeNever];
        }
    }

4.去掉UISearchDisplayController显示的“No Results”

   //code

for( UIView *subview in self.searchDisplayController.searchResultsTableView.subviews ) {
		if ([subview isKindOfClass:[UILabel class]]) {
            UILabel *lbl = (UILabel*)subview;
            lbl.text = @"";
        }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值