iOS優秀代碼收集

jopen 11年前發布 | 20K 次閱讀 IOS iOS開發 移動開發

 1.點擊一下確定,再點一下否定

  • (BOOL)didSelectedAction {

    _isSelect = !_isSelect;

    _nodePermission.selected = _isSelect;

    return_isSelect;

}

2.安全刪除集合中的元素

思路:因為nsarray是動態變化的,所以要安全刪除其中的元素,可以先另外建一個數組,將要刪除的元素加入到這個數組中,再一下刪除。

   - (NSArray *)filterPersonWithLastName : (NSString *)filterTest {

       Person *person = [[Person  alloc] init];

       NSMutableArray  *personList = [ person creatTempraryList ] ;

       NSLog (@ "before");

       [self  printingPersonArray : personList ]; //加入對象到數組中

       NSMutableArray *personsToRemove = [NSMutableArray  array] ;

       for ( Person *person  in  personList){

               if  (filterTest  &&  [filterTest  rangeOfString :person.lastName    options:NSLiteralSearch].length  == 0 )    //判斷 如果不符合的person將添加進刪除數組

                  [ personsToRemove   addObject : person];

           }

           [personList  removeObjectInArray : personsToRemove ] ;

          NSLog (@"after");

           [ self  printingPersonArray:personList ];

           [ person release];

           return  personList;

   }





3.獲取隨即數

常用方法 :arc4random

1、獲取一個隨機整數范圍在:[0,100)包括0,不包括100

int x = arc4random() % 100;

2、 獲取一個隨機數范圍在:[500,1000),包括500,不包括1000

int y = (arc4random() % 501) + 500;

3、獲取一個隨機整數,范圍在[from,to),包括from,不包括to

-(int)getRandomNumber:(int)from to:(int)to

{

return (int)(from + (arc4random() % (to – from + 1)));

}

4.NSArray不能保證沒有重復元素,這樣就可以用NSSet來剔除數組中的重復元素

NSSet *uniqueElements = [ NSSet setWithArray :array ];

for (id element in uniqueElements ){

   //do  something

}

5.比較

  • (BOOL)isEqual:(id)other {

    if (other == self)

     returnYES;
    
    

    if (!other || ![other isKindOfClass:[selfclass]])

     returnNO;
    
    

    return [selfisEqualToSelectingItem:other];

}

5.關于custom類型的button顯示不了title

UIButtonTypeCustom確實是一個自定義的按鈕類型。設置為它的默認值是沒有意義的值。如果你想顯示的話,你必須設置一個非透明的背景顏色或它的標題顏色:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setFrame:CGRectMake(x, y, width, height)];

[button setTitle:@"Button" forState:UIControlStateNormal];

// Set visible values [button setBackgroundColor:[UIColor greenColor]];

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[someSuperview addSubview:button];

  1. 內存管理的問題

這個例子很能解決些問題 -(void) viewDidLoad{ //初始化

Child *temp = [[Child alloc] init]; //引用計數為1 self.child = temp;//引用計數加1,現在是2 [temp release];//引用計數減1,現在1,不為0就不會被釋放 //self.child=[[[Child alloc] init]autorelease]; 如果是這樣一定要加上autorelease,否則會泄露。 }

-(void) dealloc{ [cihld release]; //是否用? 不用加此行會不會泄露?疑惑 //必須要釋放,執行完詞語后引用計數為0 //self.child = nil //也可以這樣釋放,這個可以仔細去看看retain,assign,copy等的用法含義 [super dealloc]; } </pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!