iOS開發中那些容易被我們忽略的代碼,常用代碼集合

 

退回輸入鍵盤

- (BOOL) textFieldShouldReturn:(id)textField{ [textField resignFirstResponder];

}

 

CGRect

CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形 NSStringFromCGRect(someCG) CGRect 結構轉變爲格式化字符串; CGRectFromString(aString) 由字符串恢復出矩形;

CGRectInset(aRect) 創建較小或較大的矩形(中心點相同),+較小 -較大 CGRectIntersectsRect(rect1, rect2) 判斷兩矩形是否交叉,是否重疊 CGRectZero 高度和寬度爲零的/位於(0,0)的矩形常量

CGPoint & CGSize

CGPoint aPoint = CGPointMake(x, y); CGSize aSize = CGSizeMake(width, height);

 

設置透明度

[myView setAlpha:value]; (0.0 < value < 1.0)

 

設置背景色

[myView setBackgroundColor:[UIColor redColor]];

(blackColor;darkGrayColor;lightGrayColor; whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor; magentaColor;orangeColor;purpleColor; brownColor; clearColor; )

 

 

自定義顏色

UIColor *newColor = [[UIColor alloc]

                     initWithRed:(float) green:(float) blue:(float) alpha:(float)];

0.0~1.0 

 

豎屏

320X480

 

橫屏

480X320

 

狀態欄高 (顯示時間和網絡狀態) 20 像素

 

導航欄、工具欄高(返回) 44 像素

 

隱藏狀態欄

[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]

 

橫屏

[[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

 

屏幕變動檢測

orientation == UIInterfaceOrientationLandscapeLeft

 

全屏

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

 

自動適應父視圖大小:

aView.autoresizingSubviews = YES;

aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |

                          UIViewAutoresizingFlexibleHeight);

 

定義按鈕

UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal]; scaleUpButton.frame = CGRectMake(40, 420, 100, 40);

[scaleUpButton addTarget:self

                  action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside];

設置視圖背景圖片

UIImageView *aView;

[aView setImage:[UIImage imageNamed:@”name.png”]]; view1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"image1.png"]];

 

 

活動表單

<UIActionSheetDelegate>

- (IBActive) someButtonPressed:(id) sender {

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@”Are you sure?”

                                                             delegate:self

                                                    cancelButtonTitle:@”No way!” destructiveButtonTitle:@”Yes, I’m Sure!” otherButtonTitles:nil];

    [actionSheet showInView:self.view];

    [actionSheet release]; }

 

警告視圖

<UIAlertViewDelegate>

- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex

{

    if(buttonIndex != [actionSheet cancelButtonIndex]) {

        NSString *message = [[NSString alloc] initWithFormat:@”You can breathe easy, everything went OK.”];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Something was done”

                              [alert show]; [alert release]; [message release];

                              }

}

 

 

動畫效果

-(void)doChange:(id)sender {

  if(view2 == nil)

  {

      [self loadSec];

  }

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:1];

    [UIView setAnimationTransition:([view1 superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRigh t)forView:self.view cache:YES];

    if([view1 superview]!= nil) {

        [view1 removeFromSuperview]; [self.view addSubview:view2];

    }else {

        [view2 removeFromSuperview]; [self.view addSubview:view1]; }

    [UIView commitAnimations];

}

                              Table View <UITableViewDateSource> #pragma mark -

#pragma mark Table View Data Source Methods //指定分區中的行數,默認爲 1

                              - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

        {

            return [self.listData count]; }

                              設置每一行 cell 顯示的內容

                              - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

        {

            static NSString *SimpleTableIndentifier = @"SimpleTableIndentifier"; UITableViewCell *cell = dequeueReusableCellWithIdentifier:SimpleTableIndentifier];

            if (cell == nil) {

                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIndentifier]

                        autorelease];

            }

            UIImage *image = [UIImage imageNamed:@"13.gif"]; cell.imageView.image = image;

            [tableView

             

             NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row];

             cell.textLabel.font = [UIFont boldSystemFontOfSize:20];

             if(row < 5)

             cell.detailTextLabel.text = @"Best friends"; else

             cell.detailTextLabel.text = @"friends"; return cell;

             }

 

 

 

 

判斷郵箱格式是否正確的代碼

利用正則表達式驗證

-(BOOL)isValidateEmail:(NSString *)email

{

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];

    return [emailTest evaluateWithObject:email];

}

 

圖片壓縮

用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];

 

壓縮圖片

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize

{

    Create a graphics image context

    UIGraphicsBeginImageContext(newSize);

    Tell the old image to draw in this newcontext, with the desired

    new size

    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    Get the new image from the context

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    End the context

    UIGraphicsEndImageContext();

    Return the new image.

    return newImage;

}

 

親測可用的圖片上傳代碼

- (IBAction)uploadButton:(id)sender {

    UIImage *image = [UIImage imageNamed:@"1.jpg"]; 圖片名

    NSData *imageData = UIImageJPEGRepresentation(image,0.5);壓縮比例

    NSLog(@"字節數:%i",[imageData length]);

    post url

    NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet";

    服務器地址

    setting up the request object now

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;

    [request setURL:[NSURL URLWithString:urlString]];

    [request setHTTPMethod:@"POST"];

   

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];

 

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];

 

    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];

 

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

 

    [body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 上傳上去的圖片名字

 

    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

 

    [body appendData:[NSData dataWithData:imageData]];

 

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

 

    [request setHTTPBody:body];

 

    NSLog(@"1-body:%@",body);

    NSLog(@"2-request:%@",request);

 

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

 

    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

 

    NSLog(@"3-測試輸出:%@",returnString);

    

    imageView加載圖片

    

    UIImage *myImage = [UIImage imageNamed:@"1.jpg"];

    [imageView setImage:myImage];

    [self.view addSubview:imageView];

    

   對圖庫的操作

    選擇相冊:

    

    UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera;

    if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        sourceType=UIImagePickerControllerSourceTypePhotoLibrary;

    }

    UIImagePickerController * picker = [[UIImagePickerControlleralloc]init];

    picker.delegate = self;

    picker.allowsEditing=YES;

    picker.sourceType=sourceType;

    [self presentModalViewController:picker animated:YES];

    

    選擇完畢:

    

    -(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info

    {

        [picker dismissModalViewControllerAnimated:YES];

        UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];

        [self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];

    }

    -(void)selectPic:(UIImage*)image

    {

        NSLog(@"image%@",image);

        imageView = [[UIImageView alloc] initWithImage:image];

        imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);

        [self.viewaddSubview:imageView];

        [self performSelectorInBackground:@selector(detect:) withObject:nil];

    }

    

 

detect爲自己定義的方法,編輯選取照片後要實現的效果

    取消選擇:

    

    -(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker

    {

        [picker dismissModalViewControllerAnimated:YES];

    }

    

    跳到下個View

    

    nextWebView = [[WEBViewController alloc] initWithNibName:@"WEBViewController" bundle:nil];

    [self presentModalViewController:nextWebView animated:YES];

    創建一個UIBarButtonItem右邊按鈕

    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右邊" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];

    [self.navigationItem setRightBarButtonItem:rightButton];

    設置navigationBar隱藏

    self.navigationController.navigationBarHidden = YES;

    iOS開發之UIlabel多行文字自動換行 (自動折行)

    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(10, 100, 300, 180)];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 150)];

    label.text = @"Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! !";

    背景顏色爲紅色

    label.backgroundColor = [UIColor redColor];

    設置字體顏色爲白色

    label.textColor = [UIColor whiteColor];

    文字居中顯示

    label.textAlignment = UITextAlignmentCenter;

    自動折行設置

    label.lineBreakMode = UILineBreakModeWordWrap;

    label.numberOfLines = 0;

    

   代碼生成button

   

    CGRect frame = CGRectMake(0, 400, 72.0, 37.0);

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    button.frame = frame;

    [button setTitle:@"新添加的按鈕" forState: UIControlStateNormal];

    button.backgroundColor = [UIColor clearColor];

    button.tag = 2000;

    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

    

   讓某個控件在View的中心位置顯示

  (某個控件,比如labelViewlabel.center = self.view.center;

    

   好看的文字處理

    

    tableViewcelltextLabel爲例子:

    

    cell.backgroundColor = [UIColorscrollViewTexturedBackgroundColor];

    設置文字的字體

    cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];

    設置文字的顏色

    cell.textLabel.textColor = [UIColor orangeColor];

    設置文字的背景顏色

    cell.textLabel.shadowColor = [UIColor whiteColor];

    設置文字的顯示位置

    cell.textLabel.textAlignment = UITextAlignmentCenter;

    

    隱藏Status Bar

    讀者可能知道一個簡易的方法,那就是在程序的viewDidLoad中加入

    [[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];

    

   更改AlertView背景

     UIAlertView *theAlert = [[[UIAlertViewalloc] initWithTitle:@"Atention"

                                                       message: @"I'm a Chinese!"

                                                      delegate:nil

                                             cancelButtonTitle:@"Cancel"

                                             otherButtonTitles:@"Okay",nil] autorelease];

    [theAlert show];

    UIImage *theImage = [UIImageimageNamed:@"loveChina.png"];

    theImage = [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];

    CGSize theSize = [theAlert frame].size;

    UIGraphicsBeginImageContext(theSize);

    [theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];這個地方的大小要自己調 

    整,以適應alertview的背景顏色的大小。

    theImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    theAlert.layer.contents = (id)[theImage CGImage];

    

    鍵盤透明

    textField.keyboardAppearance = UIKeyboardAppearanceAlert;

    

    狀態欄的網絡活動風火輪是否旋轉

    [UIApplication sharedApplication].networkActivityIndicatorVisible,默認值是NO

    

    截取屏幕圖片

    創建一個基於位圖的圖形上下文並指定大小爲CGSizeMake(200,400)

    

    UIGraphicsBeginImageContext(CGSizeMake(200,400));

    renderInContext 呈現接受者及其子範圍到指定的上下文

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    返回一個基於當前圖形上下文的圖片

    UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();

    移除棧頂的基於當前位圖的圖形上下文

    UIGraphicsEndImageContext();

    png格式返回指定圖片的數據

    imageData = UIImagePNGRepresentation(aImage);

    

    更改cell選中的背景

    UIView *myview = [[UIView alloc] init];

    myview.frame = CGRectMake(0, 0, 320, 47);

    myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];

    cell.selectedBackgroundView = myview;

    

   顯示圖像 

    CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);

    UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];

    [myImage setImage:[UIImage imageNamed:@"myImage.png"]];

    myImage.opaque = YES; opaque是否透明

    [self.view addSubview:myImage];

    

   能讓圖片適應框的大小(待確認)

    NSString*imagePath = [[NSBundle mainBundle] pathForResource:@"XcodeCrash"ofType:@"png"];

    UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];

    UIImage *newImage= [image transformWidth:80.f height:240.f];

    UIImageView *imageView = [[UIImageView alloc]initWithImage:newImage];

    [newImagerelease];

    [image release];

    [self.view addSubview:imageView];

    

   實現點擊圖片進行跳轉的代碼:生成一個帶有背景圖片的button,給button綁定想要的事件!

    UIButton *imgButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 120, 120)];

    [imgButton setBackgroundImage:(UIImage *)[self.imgArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];

    imgButton.tag=[indexPath row];

    [imgButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    

 

 

 

多線程和結束後的更新UI操作

dispatch_async(dispatch_get_global_queue(0, 0), ^{

    耗時操作

  

    dispatch_async(dispatch_get_main_queue(), ^{

        更新UI操作

 

    });

    

});

 

 

修改PlaceHolder的默認顏色

[username_text setValue:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5] forKeyPath:@"_placeholderLabel.textColor"];

 

 

頁面上移解決文本框被鍵盤彈出擋住的問題

textfield的函數

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [username_text resignFirstResponder];

    [password_text resignFirstResponder];

    When the user presses return, take focus away from the text field so that the keyboard is dismissed.

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);

    self.view.frame = rect;

    [UIView commitAnimations];

}

 

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    When the user presses return, take focus away from the text field so that the keyboard is dismissed.

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);

    self.view.frame = rect;

    [UIView commitAnimations];

    [textField resignFirstResponder];

    return YES;

}

 

- (void)textFieldDidBeginEditing:(UITextField *)textField

{

    CGRect frame = password_text.frame;

    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//鍵盤高度216

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    float width = self.view.frame.size.width;

    float height = self.view.frame.size.height;

    if(offset > 0)

    {

        CGRect rect = CGRectMake(0.0f, -offset,width,height);

        self.view.frame = rect;

    }

    [UIView commitAnimations];

}

 

 

 

iOS代碼加密常用加密方式,常見的iOS代碼加密常用加密方式算法包括MD5加密、AES加密、BASE64加密:

MD5 iOS代碼加密

創建MD5類,代碼如下

 

#import <Foundation/Foundation.h>

@interface CJMD5 : NSObject

 

+(NSString *)md5HexDigest:(NSString *)input;

 

@end

 

#import "CJMD5.h"

#import <CommonCrypto/CommonDigest.h>

 

@implementation CJMD5

 

+(NSString *)md5HexDigest:(NSString *)input{

    

    

    

    const char* str = [input UTF8String];

    

    unsigned char result[CC_MD5_DIGEST_LENGTH];

    

    CC_MD5(str, strlen(str), result);

    

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];

    

    

    

    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {

        

        [ret appendFormat:@"%02X",result];

        

    }

    

    return ret;

    

}

@end

 

MD5是不可逆的只有加密沒有解密,iOS代碼加密使用方式如下

NSString *userName = @"cerastes";

NSString *password = @"hello Word";

 

MD5加密

NSString *md5 = [CJMD5 md5HexDigest:password];

 

NSLog(@"%@",md5);

END

 

AES加密iOS代碼加密

AES加密iOS代碼加密使用方法

 

AES加密

NSString *encryptedData = [AESCrypt encrypt:userName password:password];加密

 

NSString *message = [AESCrypt decrypt:encryptedData password:password]; 解密

 

NSLog(@"加密結果 = %@",encryptedData);

 

NSLog(@"解密結果 = %@",message);

END

 

BASE64加密iOS代碼加密

BASE64加密iOS代碼加密添加如下方法

 

.h

 

+ (NSString*)encodeBase64String:(NSString *)input;

 

+ (NSString*)decodeBase64String:(NSString *)input;

 

+ (NSString*)encodeBase64Data:(NSData *)data;

 

+ (NSString*)decodeBase64Data:(NSData *)data;

 

.m

 

+ (NSString*)encodeBase64String:(NSString * )input {

    

    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    

    data = [GTMBase64 encodeData:data];

    

    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    return base64String;

    

}

 

 

+ (NSString*)decodeBase64String:(NSString * )input {

    

    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    

    data = [GTMBase64 decodeData:data];

    

    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    return base64String;

    

}

 

+ (NSString*)encodeBase64Data:(NSData *)data {

    

    data = [GTMBase64 encodeData:data];

    

    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    return base64String;

    

}

 

+ (NSString*)decodeBase64Data:(NSData *)data {

    

    data = [GTMBase64 decodeData:data];

    

    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    

    return base64String;

    

}

 

BASE64加密iOS代碼加密使用方法

BASE64加密

NSString *baseEncodeString = [GTMBase64 encodeBase64String:password];

 

NSString *baseDecodeString = [GTMBase64 decodeBase64String:baseEncodeString];

 

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

 

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

 

RSA加密:

RSA是目前最有影響力的公鑰加密算法,它能夠抵抗到目前爲止已知的絕大多數密碼攻擊,已被ISO推薦爲公鑰數據加密標準。

 

RSA公開密鑰密碼體制。所謂的公開密鑰密碼體制就是使用不同的加密密鑰與解密密鑰,是一種由已知加密密鑰推導出解密密鑰在計算上是不可行的密碼體制。

通常是先生成一對RSA 密鑰,其中之一是保密密鑰,由用戶保存;另一個爲公開密鑰,可對外公開,甚至可在網絡服務器中註冊。爲提高保密強度,RSA密鑰至少爲500位長,一般推薦使用1024位。這就使加密的計算量很大。爲減少計算量,在傳送信息時,常採用傳統加密方法與公開密鑰加密方法相結合的方式,即信息採用改進的DESIDEA對話密鑰加密,然後使用RSA密鑰加密對話密鑰和信息摘要。對方收到信息後,用不同的密鑰解密並可覈對信息摘要。

RSA算法是第一個能同時用於加密和數字簽名的算法,也易於理解和操作。RSA是被研究得最廣泛的公鑰算法.

 

RSA算法是一種非對稱密碼算法,所謂非對稱,就是指該算法需要一對密鑰,使用其中一個加密,則需要用另一個才能解密。

 

RSA的算法涉及三個參數,ne1e2

其中,n是兩個大質數pq的積,n的二進制表示時所佔用的位數,就是所謂的密鑰長度。

e1e2是一對相關的值,e1可以任意取,但要求e1(p-1*(q-1)互質;再選擇e2,要求(e2*e1mod((p-1*(q-1))=1

ne1,(ne2)就是密鑰對。其中(ne1)爲公鑰,(ne2)爲私鑰。[1]

RSA加解密的算法完全相同,設A爲明文,B爲密文,則:A=B^e2 mod nB=A^e1 mod n;(公鑰加密體制中,一般用公鑰加密,私鑰解密)

e1e2可以互換使用,即:

A=B^e1 mod nB=A^e2 mod n;

 

1)本地數據加密

NSUserDefaultssqlite存儲文件數據加密,保護帳號和關鍵信息。)URL編碼加密

對程序中出現的URL進行編碼加密,防止URL被靜態分析

 

2)網絡傳輸數據加密

對客戶端傳輸數據提供加密方案,有效防止通過網絡接口的攔截獲取

 

3)方法體,方法名高級混淆

對應用程序的方法名和方法體進行混淆,保證源碼被逆向後無法解析代碼

 

4)程序結構混排加密

對應用程序邏輯結構進行打亂混排,保證源碼可讀性降到最低

 

返回指定範圍的隨機數(m-n之間)的公式

Math.random()*(n-m)+m

 

防止被Iframe嵌套

if(top != self){

    location.href = ”about:blank”;

}

 

/**

 *  HTTP GET 請求

 **/

+(NSData *) doHttpGet:(NSString *)url

{

    NSURL *uri = [NSURL URLWithString:url];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uri];

    [request setHTTPMethod: @"GET" ];

    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

    return returnData;

}

 

/**

 *  HTTP POST請求

 **/

+(NSData *) doHttpPost:(NSString *)url withString:(NSString *)param

{

    NSData *data = nil;

    if(param != nil && [param isEqualToString:@""] == NO){

        param = [param stringByAddingPercentEscapesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];

        data = [param dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];

    }

    //調用withParam NSData*類型的方法.

    return [self doHttpPost:url withParam:data];

}

 

 

/**

 *  HTTP POST請求

 **/

+(NSData *) doHttpPost:(NSString *)url withParam:(NSData *)param

{

    新建請求

    NSURL *uri = [NSURL URLWithString:url];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uri cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:40.0];

    設置請求參數

    [request setHTTPMethod:@"POST"];

    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    if(param != nil)

        [request setHTTPBody:param];

    打開訪問網絡的狀態提示

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    請求鏈接

    NSError *error = nil;

    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSLog(@"%d: %@", error.code, error.description);

    關閉訪問網絡的狀態提示

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    返回結果

    return retData;

}

 

 

/**

 *  獲取網絡圖片

 **/

+(UIImage *) getImageFromUrl:(NSString *)url

{

    if(url == nil || [url isEqualToString:@""]){

        return nil;

    }

    url = StringByTrimWhiteSpace(url);

    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];

    UIImage *image =[[UIImage alloc] initWithData:imageData];

    return image;

}

 

/**

 *  獲取網絡圖片的內容

 **/

+(NSData *)getImageDataFromUrl:(NSString *)url

{

    if(url == nil || [url isEqualToString:@""]){

        return nil;

    }

    

    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url]];

    return imageData;

}

 

#pragma mark - 字符串處理

/**

 *  利用正則表達示獲取字符串的匹配結果

 **/

+(NSString *) getRegExpressResult:(NSString *)source regExp:(NSString *)regExp

{

    NSString *temp = [NSString stringWithFormat:@"%@", source];

    

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];

    

    if (regex != nil) {

        NSTextCheckingResult *firstMatch = [regex firstMatchInString:temp options:0 range:NSMakeRange(0, [temp length])];

        

        if (firstMatch) {

            NSRange resultRange = [firstMatch rangeAtIndex:0];

            截取數據

            NSString *result = [temp substringWithRange:resultRange];

            返回結果

            return result;

        }

    }

    return @"";

}

 

 

/**

 *  匹配字符串中整個HTML標記的內容

 **/

+(NSString *) getHtmlText:(NSString *)source tagName:(NSString *)tag

{

    NSString *regexp = [NSString stringWithFormat:@"<\\s*%@\\s+([^>]*)\\s*>([^/%@>]*</%@>)?", tag, tag, tag];

    return [BaseFunction getRegExpressResult:source regExp:regexp];

}

 

 

/**

 *  匹配HTML標記內容中的屬性值

 **/

+(NSString *) getHtmlTagAttr:(NSString *)tagContext attrName:(NSString *)attr

{

    NSString *regexp = [NSString stringWithFormat: @"%@\\s*=\\s*?(['\"][^'\"]*?)['\"]", attr];

    NSString *result = [BaseFunction getRegExpressResult:tagContext regExp:regexp];

    替換

    NSString *oldstr = [NSString stringWithFormat:@"%@=\"", attr];

    NSString *newstr = [result stringByReplacingOccurrencesOfString:oldstr withString:@""];

    newstr = [newstr substringToIndex:[newstr length] - 1];

    return newstr;

}

 

/**

 *  獲取HTML標記的文本

 **/

+(NSString *) getHTmlTagText:(NSString *)tagContext

{

    NSString *regExp = @"<\\s*\\w+\\s+([^>]*)\\s*>";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];

    

    NSTextCheckingResult *firstMatch = [regex firstMatchInString:tagContext options:0 range:NSMakeRange(0, [tagContext length])];

    NSRange resultRange = [firstMatch rangeAtIndex:0];

    NSString *newStr = [tagContext substringFromIndex:resultRange.length];

    

    regExp = @"</\\w+\\s*>";

    regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];

    firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, [newStr length])];

    resultRange = [firstMatch rangeAtIndex:0];

    

    return [newStr substringToIndex:resultRange.location];

}

 

/**

 *  替換HTML標籤

 **/

+(NSString *) replaceHtmlTag:(NSString *)source

{

    source = [BaseFunction replaceString:source byRegexp:@"<[^>]+>"];

    return [BaseFunction replaceString:source byRegexp:@"</[^>]+>"];

}

 

+(NSString *) replaceString:(NSString *)source byRegexp:(NSString *)exp

{

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:0 error:nil];

    

    if(regex == nil)

        return source;

    

    NSString *ret = [NSString stringWithFormat:@"%@", source];

    NSArray *array = [regex matchesInString:ret options:NSMatchingReportProgress range:NSMakeRange(0, [ret length])];

    for(int i = (int)[array count] - 1; i >= 0; i--)

    {

        NSTextCheckingResult *tcr = [array objectAtIndex:i];

        NSRange range = [tcr range];

        ret = [ret stringByReplacingCharactersInRange:range withString:@""];

    }

    return ret;

}

 

 

/**

 *  正則驗證

 **/

+(BOOL) string:(NSString *)source MatchRegex:(NSString *) exp

{

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", exp];

    return [predicate evaluateWithObject:source];

}

 

 

/**

 *  獲取正則表達式中匹配的個數

 **/

+ (NSInteger) getMatchCount:(NSString *)text inRegx:(NSString *)exp

{

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:0 error:nil];

    

    int count = 0;

    if (regex != nil) {

        NSArray *array = [regex matchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, [text length])];

        

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

        {

            NSTextCheckingResult *tcr = [array objectAtIndex:i];

            NSRange range = [tcr range];

            count += range.length;

        }

    }

    return count;

}

 

 

/**

 *  替換XML敏感字符

 **/

+ (NSString *) replaceXMLSensitiveLettler:(NSString *)text

{

    NSString *tmp = [text stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];

    tmp = [tmp stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];

    tmp = [tmp stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];

    return tmp;

}

 

/**

 *  分離座標

 **/

+(void) separateCoordinate:(NSString *)coord lat:(NSString **)lat lng:(NSString **)lng

{

    *lng = @"", *lat = @"";

    驗證數據的合法性

    if(coord == nil){ return; }

    coord = StringByTrimWhiteSpace(coord);

    if(IsStringEmpty(coord)){

        return;

    }

    

    將座標分開

    NSArray *coordArray = [coord componentsSeparatedByString:@","];

    if([coordArray count]>0)

        *lng = [coordArray objectAtIndex:0];

        if([coordArray count]>1)

            *lat = [coordArray objectAtIndex:1];

            }

 

 

/**

 *  從文件路徑中分解出文件名

 **/

+ (NSString *) splitFileNameForPath:(NSString *)filePath

{

    NSArray *array = [filePath componentsSeparatedByString:@"/"];

    return [array lastObject];

}

 

 

/**

 *  從文件路徑中分解出文件的擴展名

 **/

+ (NSString *) getFileExtension:(NSString *)filePath

{

    NSString *fileName = [self splitFileNameForPath:filePath];

    NSArray *array = [fileName componentsSeparatedByString:@"."];

    return [NSString stringWithFormat:@".%@",[array lastObject]];

}

 

/**

 *  獲取設備型號

 **/

+ (NSString *) platform

{

    size_t size;

    sysctlbyname("hw.machine", NULL, &size, NULL, 0);

    char *machine = (char *)malloc(size);

    sysctlbyname("hw.machine", machine, &size, NULL, 0);

    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];

    free(machine);

    NSRange range = [platform rangeOfString:@","];

    return [platform substringToIndex:range.location];

}

 

 

/**

 *  MD5加密

 **/

+ (NSString *)md5Digest:(NSString *)str {

    const char *cStr = [str UTF8String];

    unsigned char result[CC_MD5_DIGEST_LENGTH];

    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call

    NSMutableString *md5Result = [[NSMutableString alloc] init];

    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {

        [md5Result appendFormat:@"%02x", result[i]];

    }

    

    return md5Result;

        return [NSString stringWithFormat:

                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",

                result[0], result[1], result[2], result[3],

                result[4], result[5], result[6], result[7],

                result[8], result[9], result[10], result[11],

                result[12], result[13], result[14], result[15]];

}

 

+ (NSString *)SHA1:(NSString *)str {

    const char *cStr = [str UTF8String];

    NSData *data = [NSData dataWithBytes:cStr length:str.length];

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);

    NSMutableString *result = [[NSMutableString alloc] init];

    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {

        [result appendFormat:@"%02x", digest[i]];

    }

    

    return result;

}

 

判斷是否爲整形

+ (BOOL)isPureInt:(NSString *)string{

    NSScanner* scan = [NSScanner scannerWithString:string];

    int val;

    return [scan scanInt:&val] && [scan isAtEnd];

}

 

判斷是否爲浮點形

+ (BOOL)isPureFloat:(NSString *)string{

    NSScanner* scan = [NSScanner scannerWithString:string];

    float val;

    return [scan scanFloat:&val] && [scan isAtEnd];

}

 

/**

 *  版本比較

 **/

+ (BOOL)isVersion:(NSString*)versionA biggerThanVersion:(NSString*)versionB

{

    NSArray *arrayNow = [versionB componentsSeparatedByString:@"."];

    NSArray *arrayNew = [versionA componentsSeparatedByString:@"."];

    BOOL isBigger = NO;

    NSInteger i = arrayNew.count > arrayNow.count? arrayNow.count : arrayNew.count;

    NSInteger j = 0;

    BOOL hasResult = NO;

    for (j = 0; j < i; j ++) {

        NSString* strNew = [arrayNew objectAtIndex:j];

        NSString* strNow = [arrayNow objectAtIndex:j];

        if ([strNew integerValue] > [strNow integerValue]) {

            hasResult = YES;

            isBigger = YES;

            break;

        }

        if ([strNew integerValue] < [strNow integerValue]) {

            hasResult = YES;

            isBigger = NO;

            break;

        }

    }

    if (!hasResult) {

        if (arrayNew.count > arrayNow.count) {

            NSInteger nTmp = 0;

            NSInteger k = 0;

            for (k = arrayNow.count; k < arrayNew.count; k++) {

                nTmp += [[arrayNew objectAtIndex:k]integerValue];

            }

            if (nTmp > 0) {

                isBigger = YES;

            }

        }

    }

    return isBigger;

}

 

 

 

Reveal使用

1. Build Settings 搜索Other

Other Linker Flags設置爲 -ObjC

 

2. Reveal.framework拖到項目中即可

~/資源庫/Caches/

找到com.ittybittyapps.Reveal文件夾刪除

 

~/資源庫/Preferences/

 

找到com.ittybittyapps.Reveal.plist刪除

 

又可以使用30

 

UILabel設置多種字體、顏色

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed Stringtry your best to test attributed string text"];

 

[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];

 

[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];

 

[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];

 

[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(0, 5)];

 

[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(6, 12)];

 

[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(19, 6)];

 

UILabel *attrLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 320 - 40, 90)];

 

attrLabel.attributedText = str;

 

attrLabel.numberOfLines = 0;

 

[self.view addSubview:attrLabel];

 

 

iOS 調試方法(利用lldb

po _image  可以看到_imge 的信息

 

模擬器安裝app

xcrun simctl install booted +APP的路徑

 

文本框鍵盤遮擋問題

UINavigationControllerDelegate

_niChenText.delegate=self;

 

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

 

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

 

@property (strong,nonatomic)UITextField *SelectTextField;

 

 

鍵盤顯示事件

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

    

    

    

    獲取鍵盤高度,在不同設備上,以及中英文下是不同的

    

    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    

    

    

    計算出鍵盤頂端到inputTextView panel底端的距離(加上自定義的緩衝距離INTERVAL_KEYBOARD)

    

    CGFloat offset = (_SelectTextField.frame.origin.y+_SelectTextField.frame.size.height+50) - (self.view.frame.size.height - kbHeight);

    

    

    

    取得鍵盤的動畫時間,這樣可以在視圖上移的時候更連貫

    

    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    

    

    將視圖上移計算好的偏移

    

    if(offset > 0) {

        

        [UIView animateWithDuration:duration animations:^{

            

            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);

            

        }];

        

    }

    

}

 

 

鍵盤消失事件

- (void) keyboardWillHide:(NSNotification *)notify {

    

    鍵盤動畫時間

    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    

    

    視圖下沉恢復原狀

    [UIView animateWithDuration:duration animations:^{

        

        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

        

    }];

    

}

 

- (void)textFieldDidBeginEditing:(UITextField *)textField{

    

    _SelectTextField=textField;

    

}

 

 

-(BOOL)textFieldShouldReturn:(UITextField *)textField

 

{

    

    [textField resignFirstResponder];

    

    return YES;

    

}

 

 

圖片拉神

UIImage * resizeImage=[normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];

 

背景單擊事件

@interface LCTianJianDiZhiController ()<HZAreaPickerDelegate,UIGestureRecognizerDelegate>

 

UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundOnclick)];

 

tapGestureRecognize.delegate = self;

 

[self.view  addGestureRecognizer:tapGestureRecognize];

 

-(void)backGroundOnclick

 

{

    

    [_selectDiQu setTitle:@"選擇" forState:UIControlStateNormal];

    

    [self.view endEditing:YES];

    

    [self cancelLocatePicker];

    

    

    

}

 

 

以下情況不能交互

alpha<0.01

 

hidden=yes

 

userInteracion=no

 

父視圖不允許交換,子視圖也不能

 

在父圖可見範圍內可以交換,範圍之外不能交互

UiImageView 默認不允許用戶交互

 

uitableviewcell 點擊沒有效果

cell.selectionStyle = UITableViewCellSelectionStyleNone;

 

隱藏導航欄

[self.navigationController setNavigationBarHidden:YES animated:NO];

 

隱藏標籤欄

self.tabBarController.tabBar.hidden =YES;

 

時間戳轉換爲時間

NSString *str=[_mydata[indexPath.row]valueForKey:@"appr_comment_time"];時間戳

 

NSTimeInterval time=[str doubleValue]/1000+28800;因爲時差問題要加8小時 == 28800 sec

 

NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];

 

NSLog(@"date:%@",[detaildate description]);

 

實例化一個NSDateFormatter對象

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

 

設定時間格式,這裏可以設置成自己需要的格式

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

 

NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];

 

NSLog(@"%@",currentDateStr);

 

密碼文本框secureTextEntry

 

 

把數據存儲到本地

存儲

 

獲取userDefault單例

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

 

登陸成功後把用戶名和密碼存儲到UserDefault

[userDefaults setObject:_userName.text forKey:@"name"];

 

[userDefaults setObject:_password.text forKey:@"password"];

 

[userDefaults synchronize];

 

 

調用

獲取UserDefault

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

 

_userName.text= [userDefault objectForKey:@"name"];

 

_password.text= [userDefault objectForKey:@"password"];

 

 

頁面切換的方式

從一個ViewController切換到另一個ViewController有下面幾種方法:

 

1addsubview方法切換視圖

 

self.view addSubview:(加載的新頁面);

 

相應的 [self.view removeFromSuperview];移除添加的view

 

2self.view insertSubview:(加載的新頁面) atIndex:n;

 

n的解釋:頁面都是層次疊加的,n表示加載到那一層上面

 

 

3presentModalViewController方法

 

photoNacController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

 

photoNacController.modalPresentationStyle = UIModalPresentationFullScreen;

 

self presentModalViewController:(加載的新頁面) animated:

 

modalTransitionStyle用於設置頁面切換的動畫

 

modalPresentationStyle用於設置視圖顯示的方式

 

兩種方法試試就知道用途了!

 

(4) pushViewController導航

 

[self.navigationController pushViewController:(加載的新頁面) animated:YES];

 

對應的

 

[self.navigationController popViewControllerAnimated:YES];

 

總結:系統提供了我們視圖切換的方法以及視圖切換的默認動畫,我們可以選擇這幾種方法中的去使用,也可以自定義切換的動畫animation

 

 

/** 隱藏狀態欄 */

- (BOOL)prefersStatusBarHidden

 

{

    

    return YES;

    

}

 

調整邊距,可以讓表格視圖讓開狀態欄

self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

 

 

代刪除線的UILabel

- (void)drawRect:(CGRect)rect {

    

    Drawing code

    

    [super drawRect:rect];

    

    CGContextRef context=UIGraphicsGetCurrentContext();

    

    CGContextMoveToPoint(context, 0, 8);

    

    CGContextAddLineToPoint(context, rect.size.width, rect.size.height-5);

    

    CGContextStrokePath(context);

    

}

 

xib加載時如果不顯示或出錯就可能是伸縮的問題

dropdown.autoresizingMask=UIViewAutoResizingNone;

 

 

unbutton 設置圓角邊框

 

[huoQuYanZhenMa.layer setMasksToBounds:YES];

 

[huoQuYanZhenMa.layer setCornerRadius:10.0]; 設置矩形四個圓角半徑

 

[huoQuYanZhenMa.layer setBorderWidth:1.0]; 邊框寬度

 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

 

CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });

 

[huoQuYanZhenMa.layer setBorderColor:colorref];邊框顏色

 

[self.view addSubview:huoQuYanZhenMa];

 

 

界面跳轉

- (void)pushAction{

    

    PushViewController *pushVC = [[PushViewController alloc] init];

    

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

    

    RootViewController *rootVC = (RootViewController *)self.tabBarController;

    

    [rootVC showTabBar:NO];

    

    [self.navigationController showViewController:<#(UIViewController *)#> sender:<#(id)#>]

    

}

 

- (void)presentAction{

    

    ModalViewController *modalVC = [[ModalViewController alloc] init];

    

    模態視圖

    

    [self presentViewController:modalVC animated:YES completion:nil];

    

}

 

- (void)dismissAction{

    

    [self dismissViewControllerAnimated:YES completion:nil];

    

}

 

- (void)popAction{

    

    [self.navigationController popViewControllerAnimated:YES];

    

}

 

UIStoryboard *stryBoard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];

 

[self presentViewController:[stryBoard instantiateViewControllerWithIdentifier:@"mytabBarContol"] animated:NO completion:nil];

 

 

語法約定

方法首字母大小,單詞切換用大寫

類名要大寫

初始化應用要initW~~,w一定要大些,並且前面一定是init纔行;不然self=[super init]會出錯

 

打印結構體

NSLog(@“%@”,nSStringFromRange(range));

 

代理的作用

監聽哪些不能用addTarget監聽的事件

主要用來負責兩個對象之間的消息傳遞

 

代理實現的步驟

1)成爲(子)控件的代理,父親(控制器)成爲兒子(文本框)的代理

2)遵守協議,利用智能提示具體實現

 

代理的id應該用weak 弱引用,不然會照成循環引用

 

判斷是否實現某個協議方法

 

if ([self.delegate respondsToSelector:@selector(tgFooterViewDidDowenLoadButton:)]) {

    

    [self.delegate tgFooterViewDidDowenLoadButton:self];

    

}

 

 

代理模式:是父控件(視圖控制器)監聽子控件的事件,當子控件發生某些事情時通知父控件工作

 

footerView->controller 去工作,用代理

 

conterView->footerView去工作,直接調用用footView的方法

 

不要分割線

tabQQChat.separatorStyle=UITableViewCellSeparatorStyleNone;

 

內邊距

_textView.contentEdgeInsets=UIEdgeInsetsMake(20, 20, 20, 20);

 

獲取文本的寬高

 

正文

CGFloat textX;

 

CGFloat textY=iconY;

 

CGSize textmaxSize= CGSizeMake(150, MAXFLOAT);

 

CGSize textRealSizw=[message.text boundingRectWithSize:textmaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f]} context:nil].size;

 

 

模型中數據中文亂碼

對象描述方法,類似toStrong

-(NSString *)description

 

{

    

    return [NSString stringWithFormat:@"=<%@:   %p>{answer: %@,icon:%@,title:%@,option:%@}",self.class,self ,self.answer,self.icon,self.title,self.options];

    

    

    

}

 

然後在viewDidLoad

 

NSLog(@"%@",self.question);

 

然後導入NSArrayLog.h

 

改變狀態欄的顏色

-(UIStatusBarStyle)preferredStatusBarStyle

 

{

    

    return UIStatusBarStyleLightContent;

    

}

 

隱藏返回按鈕文字

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)

 

                                                     forBarMetrics:UIBarMetricsDefault];

 

uitableVIew的背景圖片

 

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftMenu.jpg"]];

 

self.tableView.backgroundView = imageView;

 

分割線

self.tableView.separatorStyle=UITableViewCellSeparatorStyleLSingleLine;

 

刪除多餘的分割線

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//tableView刪除多餘的分割線

 

- (void)setExtraCellLineHidden: (UITableView *)tableView

 

{

    

    

    

    UIView *view = [UIView new];

    

    

    

    view.backgroundColor = [UIColor clearColor];

    

    

    

    [tableView setTableFooterView:view];

    

}

 

Cell中的代理方法

/**

 

 初始化方法

 

 

 

 使用代碼創建Cell的時候會被調用,如果使用XIB或者Storyboard,此方法不會被調用

 

 */

 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

 

 

 

/**

 

 XIB被加載之後,會自動被調用,如果使用純代碼,不會被執行

 

 */

- (void)awakeFromNib

 

 

Cell 被選中或者取消選中是都會被調用

如果是自定義Cell控件,所有的子控件都應該添加到contentView

 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated

 

UIView的常用方法:

-(voidaddSubview:(UIVIew *)view;添加一個子控件

-(voidremoveFromSuperview; 從父控件中移除

 

-(UIView *viewWithTag:(NSInteger)tag;根據tag表示尋找到對應的控件(一般是用於尋找子控件)

 

 

加載xib文件:

NSArray *array=[[NSBundle mainBundle] loadNibName:@“HMAppView”owne:nil  options:nil];

UIView *view=[array firstObject];

 

計算給定文本字符串

UILabel要換行就要給設置行爲0

 

_textView.numberOfLines=0;

 

boundingRectWithSize計算給定文本字符串所佔的區域

返回值是一個x,y = 0CGRect,w,h是計算好的寬高

 

如果要計算多行的準確高度,需要傳入NSStringDrawingUsesLineFragmentOrigin選項

 

dict用於指定字體的相關屬性的字典,UIKit框架中的第一個頭文件

 

context: nil

NSDictionary *nameDict = @{NSFontAttributeName: kNameFont};

 

CGRect nameFrame = [self.status.name boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:nameDict context:nil];

 

nameFrame.origin.x = CGRectGetMaxX(self.iconView.frame) + padding;

 

nameFrame.origin.y = padding + (self.iconView.bounds.size.height - nameFrame.size.height) * 0.5;

 

self.nameView.frame = nameFrame;

 

代碼塊存放路徑:

/Users/a625/Library/Developer/Xcode/UserData/CodeSnippets

 

 

uitableview繼承自uiscrollview

需要知道共有多少行,每一行有多高才能計算出UIscrollview的高度

知道每一行的高度,就可以計算出每一個屏幕顯示多數航,才計算出表格明細方法的執行次數

tableview .rowhight 的效率比代理更高,如果行高一樣就用屬性,不一樣用代理

 

修改控件大小:

-(IBActiontop:(UIButton *)sender{

    

    CGRect btnFrame=self.HeadBtn.Fram;

    

    btnFrame.origin-=10;

    

    self.headBtn.fram=btnFrame;

    

}

 

下面代碼錯誤的,oc規定不允許直接修改對象的結構體屬性的成員

selfheadBtn.frmae.origin.y-10

 

代碼創建按鈕:

1.創建一個自定義的按鈕

 

UIButton *btn=[UIButton buttonWithTypeCustom];

 

2.添加按鈕

 

[self.view addSubview:btn];

 

3.設置按鈕的位置和尺寸

 

btn.frame=CGRectMake(100,100,100,100);

 

4.監聽按鈕的點擊事件(點擊按鈕後就會調用selfbtnClick方法)

 

[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

 

5.設置按鈕在在默認狀態下的屬性

 

5.1默認狀態下的背景

 

[btn setBackgroundImage:[UIImage imageName@“btn_01”] forState:UIControlStateNormal];

 

5.2.設置默認狀態下的文字:千萬不要用btn.titleLabel.text=@“sdsd”;

 

[btn setTitle:@“點我啊”forState:UIControlStateNormal];

 

5.3 默認狀態的文字顏色

 

[btn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];

 

6.設置按鈕在高亮狀態下的屬性

 

6.1 高亮狀態的背景

 

[btn setBackgroupImage:[UIImage imageName:@“btn_01”] forState:UIControlStateHighlighted];

 

6.2 高亮狀態下的文字顏色

 

[btn setTitle:@“摸我幹啥”forState:UIControlStateHighlighted];

 

6.3 高亮狀態下文字顏色

 

[btn setTitleColor:[UIColor blueColor] forState:UIControlStateHightlighted];

 

修改按鍵的字體(titleLabel 是隻讀的  readonly 表示不允許修改titleLabel的指針)

 

btn.titleLabel.font=[UIFont sysTemFontOfsize 13];

 

sender.currentTitle 取出當前按鈕的標題文字

 

CGRectGetMaxYlable.frame);

 

frame屬性,一般不要修改,通常用於實例化控件,指定初始位置

如果需要改變控件大小,使用bounds

如果需要改變控件位置,使用center

 

@property

1.生成getter()方法

2.生成setter() 方法

3生成帶下劃線的成員變量(紀錄屬性內容)

readonly的屬性不會生成帶下劃線的成員變量

@synthesize 可以合成出來 @synthesize image_image;

 

代理的相關

1.遵守相關的協議,預先定義好方法,具體的實現工作有代理負責

<控件名稱+DataSource> 定義的數據有關的方法

<控件名稱+Delegate> 定義的與事件有關的方法,通常用來監聽控件事件的

 

2.代理方法

1> 方面名以控件名稱開口(沒有前綴) ->方便程序員編寫的時候快速找到需要的方法

2> 第一個參數是自己 ->意味着在協議方法中可以直接訪問對象的屬性,或者調用方法

3>代理方法的返回值 ->控制器向控件(委託)發送數據

 

內存管理:

控件:

如果是託線,用Weak

如果是代碼,用Strong

NString copy

數字型的int 使用Assig

 

圖片:

JPG:壓縮比較高,通常用於照片,網頁,有損壓縮,解壓縮時 對cpu消耗大,意味慢,費電

PNG: 壓縮比高,無損壓縮,

 

UIScrollView

 

self.scrollView.contentInset=UIEdgeInsetsMake(20, 20, 20, 20);

self.scrollView.showsHorizontalScrollIndicator=NO;

self.scrollView.showsVerticalScrollIndicator=NO;

 

偏移位置

self.scrollView.contentOffset=CGPointMake(100, 100);

self.scrollView.bounces=NO;取消彈簧效果

 

contentSize    會根據邊距調整offset

contentInset   不會調整offset

 

動畫的兩種方式:

1.頭尾式

[UIView beginAnimations:nil context:nil];

 

/**需要執行的動畫**/

[UIViewcommitAnimations];

 

2.Block

[UIView animateWithDuration:0.5 animations:^{

    

    /**需要執行動畫的代碼**/

    

}];

 

修改控件的位置和尺寸:

位置

frame.origin 原點

center      中心

 

尺寸:

frame.size

bounds.sizes

 

查看是否調用該函數

NSLog(“@”__func__);

 

get方法中

,如果跟自己相關的用下劃線,不相干的用self

 

 

字典轉模型

-(NSArray)appList

 

{

    

    if(appList==nil)

        

    {

        

        NSArray *array=[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] PathForResouce:@“app.plist” ofType:nil]];

        

        創建一個臨時數組

        

        NSMutableArray *arrayM=[MSMutableArray array];

        

        for(NSDictionary *dict in array)

            

        {

            

            HMAppInfo *appInfo=[[HMAppInfo alloc]init];

            

            appInfo.name=dict[@“name”];

            

            appInfo.icon   =dict[@“icon”];

            

            [arrayM oddObject:appInfo];

            

            

        }

        

        將臨時數組複製給屬性

        

        _appList=arrayM;

        

    }

    

    return _appList;

    

}

 

使用時:

先實例化:HMAppInfo *appInfo=self.appList[i];

再使用: icon.image=[UIImage imageName:appInfo.icon];

 

UITextView 光標不再最開始位置

self.automaticallyAdjustsScrollViewInsets = NO;

 

設置標籤欄屬性

UITabBarItem*item =self.tabBarController.tabBar.items[0];

 

UIImage*imageNomal = [[UIImage imageNamed:@"table_zhuye_off"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

 

item.image= imageNomal;

 

UIImage*imageSelected = [[UIImage imageNamed:@"table_zhuye_on"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

 

item.selectedImage= imageSelected;

 

self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];

 

self.tabBarController.tabBar.translucent = false關閉透明

 

self.tabBarController.tabBar.tintColor = [UIColor colorWithRed:0.359 green:0.902 blue:0.296 alpha:1.000];

 

 

 

退出鍵盤

方法一:[self.textfield resigFirstResponder;

方法二:[self.view endEditing:YES];Yes是否性關閉鍵盤

 

transform修改控件的位移(位置),縮放,旋轉

創建一個transform屬性相對初始

CGAffineTransForm CGAffineTransformMakeTransLation(CGFloat tx,CGFloat ty);左右移動

CGAffineTransForm CGAffineTransformMakeScale(CGFloat sx,CGFloat sy);放大縮小

CGAffineTransForm CGAffineTransformMakeRotaton(CGFloat angle);  angle是弧度制,,排M_PI_4

 

在某個transform的基礎上進行疊加

CGAffienTransForm CGAffienTransformTransSlate(CGAffienTransForm t,CGFloat tx.CGFloat ty);

CGAffienTransForm CGAffienTransFormScale(CGAffienTransform t , CGFloat sx,CGFloat sy);

CGAffienTransForm CgAffeinTransformRotate(CGAffienTransform t,CGFloat angle);

 

清空之前設置的transForm屬性

view.transfrom=CGAffineTransformIdentity;

 

例:

self.butotn.transform=CGAffineTransForMakeTranslation(0,-100);向上平移100

NSLog(@“%@”,NSStringFromCGAffineTRansfor(self.button.transform));

self.button.transform=CGAffineTransFormRotate(self.button.transform,-M_PI_4);//逆時針旋轉45

 

UIImage加載圖片:

一個UIImage對象代表了一張圖片,一般通過Image@”圖片名加載圖片(png格式的圖片可以省略拓展名)

 

UIImage image=[UI image imageName@“btn_01”];

 

imageNamed :圖像是實例化之後由系統 負責,

 

String *path=[[NSBundle mainBundle] pathForResource:imageName];

 

可以使用:UIImae *image=UIImage imageWithContentsOfFile:path];//但是不能放在images.xcassets

 

解析Plist文件

1.獲取Plist文件路徑

NSBundle *bundle=[NSBundle MianBundle];

NSString *path=[bundle pathForResource:@“imageData” ofType:@“plist”];

 

2.懶加載Plist文件

_image=[NSArray arrayWithContentOfFile:path];

 

-(NSArray *)image

 

{

    

    if(_image==nil){

        

        NSBundle *bundle=[NSBundle MianBundle];

        

        NSString *path=[bundle pathForResource:@“imageData” ofType:@“plist”];

        

        _image=[NSArray arrayWithContentOfFile:path];

        

    }

    

    return _image;

    

}

 

get()懶加載

get()方法中不要在調用get()方法了,self.btn是屬於get()方法,_btn 是變量名,不屬於get()方法

在懶加載中屬於get()方法,所有懶加載中不能出現self.btn~ 不然會出現死循環

 

時鐘

scheduledTimerWithTimeInterval 方法本質上就是創建一個時鐘,

添加到運行循環的模式是DefaultRunLoopMode

 

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:@"hello timer" repeats:YES];

 

1等價

self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

 

timer添加到運行循環

模式:默認的運行循環模式

[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];

 

self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

 

timer添加到運行循環

模式:NSRunLoopCommonModes的運行循環模式(監聽滾動模式)

[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

 

停止時鐘

[self.timer invalidate];

 

枚舉

枚舉類型本質上是整數,定義的時候,如果指定了第一個整數值,然後後面的就會遞增

枚舉時解決魔法數字的很好工具

typedef enum

KmovingDirTop=10;

KmovingDirBottom;

KmovingDirLeft;

KmovingDirRigth

KmoingDir;

 

通知中心傳值:

 

發送通知

[[NSNotificationCenter defaultCenter]postNotificationName:@"categoryDidChanged" object:nil userInfo:@{@"categoryModel":_seletedModel}];

 

接受:

 

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(categoryChange:) name:@"categoryDidChanged" object:nil];

 

- (void)categoryChange:(NSNotification*)noti{

    

    CategoriyModel *md = (CategoriyModel*)noti.userInfo[@"categoryModel"];

    

    NSString *str = noti.userInfo[@"subCategoryName"];

    

    NSLog(@"左表:%@",md.name);

    

    NSLog(@"右表:%@",str);

    

    

    

}

 

- (void)dealloc{

    

    [[NSNotificationCenter defaultCenter]removeObserver:self];

    

}

 

UITableviewCell 更新

一個section刷新

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];

 

[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

 

一個cell刷新

NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];

 

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

 

獲取屏幕高度

#define  kScreenWidth   [UIScreen mainScreen].bounds.size.width

#define kScreenHeight   [UIScreen mainScreen].bounds.size.height

 

生成隨機數

arc4random_uniform(10) => 0~9之間的隨機數

 

ARC 編譯:

-fno-objc-arc

 

AFNetworking 的使用:

1.創建

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 

2.指定解析器

      manager 默認情況下是解析 json plist

      xml 手動設置

 

    manager.responseSerializer

    manager.requestSerializer

    aplication/json  text/json

 

3.get/post 請求

接口地址 urlString

請求參數

網絡請求成功後的回調 blocks

 

[manager GET:<#(NSString *)#> parameters:<#(id)#> success:^(AFHTTPRequestOperation *operation, id responseObject) {

    

    成功後的操作

 

    operation.resposeData

 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    

    請求失敗後的操作

    NSLog(@"%@",error);  

    

}];

 

post

[manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    

    發送後的回調

    

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    

    發送失敗後的回調

    

}];

 

1. 網絡下載數據然後把數據轉爲圖片 再加載

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"image/jpeg"];

[manager GET:imageURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    

    NSLog(@"下載圖片成功!");

    

    iv.image = [UIImage imageWithData:operation.responseData];

    

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    

    NSLog(@"%@",error);

    

}];

 

 

-(void)download{

    

    &tag=1001011&telephone=18398850943&password=111111

    

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    

    [manager GET:@"http://120.25.160.35:8080/LocalGoodBrand/UserServlet" parameters:

     

     @{@"tag"           : @"100111"}

     

         success:^(AFHTTPRequestOperation *operation, id responseObject) {

             

             NSString *string=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

             

             NSData* jsonData=[string dataUsingEncoding:NSUTF8StringEncoding];

             

             _dataArray=   [NSJSONSerialization

                            

                            JSONObjectWithData:jsonData

                            

                            options:NSJSONReadingMutableContainers

                            

                            error:nil];

             

                          

         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             

             NSLog(@"Error: %@", error);

             

         }];

    

    

    

    

    

}

 

SDWebImage的使用:

[iv sd_setImageWithURL:[NSURL URLWithString:imageURL]];

 

UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundOnclick)];

 

tapGestureRecognize.delegate = self;

[self.view  addGestureRecognizer:tapGestureRecognize];

 

刪除storyboard

1.刪除storyboard

2.general 中刪除“main”

2.info 中刪除 storyboard選項

3.屏幕初始化:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  

    

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

    

    self.window.backgroundColor = [UIColor whiteColor];

    

    

    

    創建導航欄 需要傳入一個UICollectionViewController

   

    FirstViewController *fvc = [[FirstViewController alloc]init];

    

    MyNavController *nav = [[MyNavController alloc]initWithRootViewController:fvc];

    

    self.window.rootViewController = nav;//

    

    [self.window makeKeyAndVisible];

    

    return YES;

    

}

 

按鈕監聽事件:

- (void)addtarget:(id)target action:(SEL)action{

    

    [self.button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    

}

 

[first addtarget:self action:@selector(firstClick)];

 

#pragma mark - 點擊事件

- (void)firstClick{

    

    [self createPopver];

    

}

 

獲取plist文件數據

獲取plist文件地址

NSString *file = [[NSBundle mainBundle]pathForResource:@"categories.plist" ofType:nil];

 

加載plist爲數組

NSArray *plistArray = [NSArray arrayWithContentsOfFile:file];

 

關閉popview 的自動適應屏幕屬性:

pop.autoresizingMask = UIViewAutoresizingNone;

 

屏幕切換動態效果:

nav.modalPresentationStyle = UIModalPresentationFormSheet;

 

 

隱藏導航欄;

[self.navigationController setNavigationBarHidden:YES animated:YES];

 

設置tabbar的初始位置:

self.selectedIndex=button.1

 

判斷網絡連接:

OOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    

    開啓網絡指示器

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    

    基準網站

    NSURL *url = [NSURL URLWithString:@"http://baidu.com"];

    

    監聽結果回調

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];

    

    NSOperationQueue *operationQueue       = manager.operationQueue;

    

    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        

        switch (status) {

                

            case AFNetworkReachabilityStatusReachableViaWWAN:

                

            case AFNetworkReachabilityStatusReachableViaWiFi:

                

                

                

                [operationQueue setSuspended:NO];

                

                NSLog(@"有網絡");                

                

                break;

                             

                

            case AFNetworkReachabilityStatusNotReachable:

                

            default:

                

                [operationQueue setSuspended:YES];

                            

                NSLog(@"無網絡");

                

                break;

                

        }  

        

    }];

    

    開始監聽

    [manager.reachabilityManager startMonitoring];

    

    

    

    UILabel 自動換行和自適應

    要想UI Label自動換行,line設置爲0

    

    1.N行完全自適應:

    

    UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

    

    NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

    

    testLabel.numberOfLines = 0; 相當於不限制行數

    testLabel.text = txt;

    這樣不行,還需要調用 [testLabel sizeToFit];

    

    

    2.限制在N行內自適應:

    UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

    

    NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

    

    testLabel.numberOfLines = 3;  限制在3行內自適應

    

    testLabel.text = txt;

    

    [testLabel sizeToFit];

    

    結果不起作用,全部在一行顯示了。

    

    

    3.爲了實現2的需求,需要這麼做:

    CGSize maxSize = CGSizeMake(100, 21*3);

    

    UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

    

    NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

    

    CGSize labelSize = [txt sizeWithFont:testLabel.font constrainedToSize:maxSize lineBreakMode: UILineBreakModeTailTruncation];

    

    

    testLabel.frame = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, labelSize.width, labelSize.height);

    

    testLabel.text = txt;

    

    

    NSString

    創建一個字符串常量

    

    NSString *string1 = @"hello";

    

    string1 = @"hello world";

    

    NSLog(@"%@",string1);

    

    

    

    創建字符串

    NSString *string2 = [[NSString alloc] initWithString:@"hello"];

    

    initWithFormat:多個字符串拼接

    NSString *string3 = [[NSString alloc] initWithFormat:@"hello %@",string2];

    

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

    

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

    

    NSString *ss1 = [[NSString alloc] initWithFormat:@"ZHANGsan"];

    

    NSString *ss2 = [[NSString alloc] initWithFormat:@"zhangsan"];

    

    NSLog(@"[ss1 caseInsensitiveCompare:ss2]:%ld",[ss1 caseInsensitiveCompare:ss2]);

    

    

    創建空的字符串

    NSString *string4 = [[NSString alloc] init]; //等價於string4 = @"";

    

    stringWithFormat:使用類方法創建字符串對象

    

    NSString *string5 = [NSString stringWithString:@"hello"];  //等價於string5 = @"hello";

    NSString *string6 = [NSString stringWithFormat:@"hello %@",@"world"];

   

    

    使用格式化符拼接數值

    int number = 101;

    

    NSString *string7 = [NSString stringWithFormat:@"class:%d",number];

    

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

    

   

 

    字符串的比較

    NSString *s0 = @"Ediosn";

    

    NSString *s11 = @"Edison";   //s0s11的指針地址是一樣的,指向的都是常量區同一個字符串對象

 

    

    NSString *s1 = [NSString stringWithFormat:@"Ediosn"];

    

    NSString *s2 = [[NSString alloc] initWithFormat:@“Ediosn"];

    

 

    判斷s1s2的指針地址是否相等

    if (s0 == s2) {   不相等,因爲是兩個對象,指針地址不一樣

        

        NSLog(@"s0 == s2");

        

    }

    

      

    isEqualToString: 是比較兩個字符串內容是否相同

    

    if ([s0 isEqualToString:s2]) {

        

        NSLog(@"s0s2的字符串內容相同");

        

    }

    

    NSObject *obj1;

    

    NSObject *obj2;

    

    

    NSString *string8 = @"a";

    

    NSString *string9 = @"A";

    

    

    compare: 比較字符串的大小

    

    NSComparisonResult result = [string8 compare:string9];

    

    if (result == NSOrderedAscending) { 結果爲升序

        

        NSLog(@"string8 < string9");

        

    } else if(result == NSOrderedSame) {

        

        NSLog(@"string8 string9 內容一樣");

        

    } else if(result == NSOrderedDescending) {

        

        NSLog(@"string8 > string9");

        

    }

    

    

    length: 獲取字符串的長度

    NSString *string10 = @"abcdef";

    

    NSInteger len = [string10 length];

    

    NSLog(@"len = %ld",len);

    

    

    NSString *string11 = @"hELlo";

    

    uppercaseString:將字符串中的字母轉成大寫

    NSLog(@"upper:%@",[string11 uppercaseString]);

    

    uppercaseString

    NSLog(@"lower:%@",[string11 lowercaseString]);

    

    capitalizedString:首字母大寫,其他字母小寫

    NSLog(@"capitalized:%@",[string11 capitalizedString]);

    

    

    將字符串轉成基本數據類型

    NSString *string12 = @"3.14";

    

    float f = (float)string12;  錯誤

 

    floatValue:字符串中是一個浮點數值轉成float

    

    float f = [string12 floatValue];

    

    NSLog(@"floatValue:%f",f);   

    

    NSString *string13 = @"1";

    

    BOOL bo = [string13 boolValue];  //true

    

    

    

    ---------------(4)字符串截取--------------------

    

    NSString *string14 = @"abcdef";

    

    ---------------(4)字符串截取--------------------

    

    NSString *substring1 = [string14 substringToIndex:3];

    

    NSLog(@"substringToIndex:%@",substring1);

    

    

    

    substringFromIndex:從指定索引位置開始截取到末尾,包含指定的索引f

    

    NSString *substring2 = [string14 substringFromIndex:1];

    

    NSLog(@"substringFromIndex:%@",substring2);

    

    

    

    NSRange rang = {2,3};  2:指定位置  3:需要截取的長度

    

    substringWithRange:截取指定範圍的字符串

    

    NSString *substring3 = [string14 substringWithRange:rang];

    

    NSLog(@"substringWithRange:%@",substring3);

    

    

    

    NSArray *array = [string componentsSeparatedByString:@"A"]; 從字符A中分隔成2個元素的數組

    

    

    ---------------(5)拼接字符串--------------------

    

    NSString *str1 = @"Hello";

    

    NSString *str2 = @"World";

    

    NSString *str3 = @"OC!";

    

    NSString *string15 = [NSString stringWithFormat:@"%@-%@-%@",str1,str2,str3];

    

    NSLog(@"string15:%@",string15);

    

    

    

    字符串追加

    NSString *string16 = [string15 stringByAppendingString:@"-iOS"];

    

    NSString *string17 = [string15 stringByAppendingFormat:@"%@,%@",@"iOS",@"iPhone"];

    

    NSLog(@"string16:%@",string16);

    

    NSLog(@"string17:%@",string17);

    

    

    

    字符串追加

    NSString *link = @"www.iphonetrain.com/.html";

    

    rangeOfString:查找字符串所在的位置

    NSRange linkRang = [link rangeOfString:@"html"];

    

    if (linkRang.location != NSNotFound) {

        

        NSLog(@"location:%ld,length:%ld",linkRang.location,linkRang.length);

        

    }

    

    

    

    例如:能查找到@163.com,說明此郵箱是網易郵箱

    

    NSString *email = @"[email protected]";

    

    

    

    /*___________________________NSMutableString(不可變字符串)__________________________*/

    

    NSMutableString *mutableString1 = @"string";  錯誤

    NSMutableString *mutableString1 = [[NSMutableString alloc] initWithFormat:@"字符串"];

    

    insertString: 在原有的字符串基礎上插入字符串

    

    [mutableString1 insertString:@"可變" atIndex:0];

    

    NSLog(@"mutableString1:%@",mutableString1);

    

    NSMutableString *mutableString2 = [NSMutableString stringWithFormat:@"字符符符串"];

    

    rangeOfString:查找指定字符串所在的範圍

    

    NSRange rang3 = [mutableString2 rangeOfString:@"符符"];

    

    deleteCharactersInRange:根據範圍刪除指定的字符串

    

    [mutableString2 deleteCharactersInRange:rang3];

    

    NSLog(@"mutableString2:%@",mutableString2);

    

    

    

    NSMutableString *mutableString3 = [NSMutableString stringWithFormat:@"字符串"];

    

    NSRange rang4 = [mutableString3 rangeOfString:@"字符"];

    

    replaceCharactersInRange:withString:  字符串替換

    

    [mutableString3 replaceCharactersInRange:rang4

     

                                  withString:@"羊肉"];

    

    NSLog(@"mutableString3:%@",mutableString3);

    

   

    NSArray

    

    /*_________________________不可變數組(NSArray)_______________________________*/

      ---------------------1.數組的創建--------------------------

    

    NSString *s1 = @"zhangsan";

    

    NSString *s2 = @"lisi";

    

    NSString *s3 = @"wangwu";

    

    

    

    NSArray *array1 = [[NSArray alloc] initWithObjects:s1,s2,s3, nil];

    

    NSLog(@"%@",array1);

    

    

    

    類方法創建,注意:最後以nil結尾。

    NSArray *array2 = [NSArray arrayWithObjects:s1,s2,s3, nil];

    

    初始一個元素對象

    NSArray *array3 = [NSArray arrayWithObject:s1];

    

    

    

    創建一個數組,此數組中的元素來自array1

    NSArray *array4 = [NSArray arrayWithArray:array1];

    

    

    

    ---------------------2.通過下標取元素--------------------------

    

    NSString *str1 = [array4 objectAtIndex:0];

    

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

    

    

    

    ---------------------3.數組的元素個數--------------------------

    

    NSUInteger count = [array4 count];

    

    NSUInteger count2 = array4.count;  點語法等價於-> [array4 count];注意count是不能帶參數

    

    NSLog(@"count2 = %ld",count2);

    

    

    

    ---------------------4.判斷是否包含某個對象--------------------------

    

    BOOL isContains = [array4 containsObject:@"zhangsan"];

    

    NSLog(@"isContains: %d",isContains);

    

    

    

    ---------------------5.對象在數組中的索引位置--------------------------

    

    NSUInteger index = [array4 indexOfObject:@"wangwu"];

    

    NSLog(@"index = %ld",index);

    

    

    

    ---------------------6.鏈接數組中的字符串--------------------------

    

    注意:數組中的元素必須都是字符串,纔可以使用此方法

    

    NSString *joinString = [array4 componentsJoinedByString:@","];

    

    NSLog(@"join:%@",joinString); //zhangsan,lisi,wangwu

    

    

    

    ---------------------7.訪問最後一個元素--------------------------

    

    NSString *last = [array4 lastObject]; //等價於點語法:array4.lastObject;

    

    NSLog(@"last:%@",last);

    

    

    

    ---------------------8.在原來的數組上追加對象--------------------------

    

    追加之後,創建了一個新的數組

    

    NSArray *array5 = [array4 arrayByAddingObject:@"zhaoliu"];

    

    NSLog(@"array5:%@",array5);

    

    

    

    /*

     

     注意:1.數組中不能存放基本數據類型,只能存放對象

     

     2.數組越界

     

     */

    

     NSArray *array6 = [NSArray arrayWithObject:100];  //錯誤,基本數據類型不能存放到數組中

    

    

    

    int idx = 4;

    

    if (idx < array5.count) {  嚴謹的寫法,只有下標小於元素個數時,纔可以使用下標取元素

        

        [array5 objectAtIndex:idx];

        

    }

    

    ---------------xcode4.4以後對數組的創建和訪問,語法上做了優化---------------

    

    1.創建一個數組

    

    NSArray *array7 = @[s1,s2,s3];

    

    等價於NSArray *array2 = [NSArray arrayWithObjects:s1,s2,s3, nil];

    

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

    

    NSString *str = array7[0];

    

    NSLog(@"array7[0] = %@",str);

    

        

    /*_________________________可變數組(NSMutableArray)_______________________________* 

    

    NSString *t1 = @"zhangsan";

    

    NSString *t2 = @"lisi";

    

    NSString *t3 = @"wangwu";

    

   

    ---------------------1.創建可變數組--------------------------

    

    NSMutableArray *marray1 = [[NSMutableArray alloc] initWithObjects:t1,t2,t3, nil];

    

    

    創建數組時,開闢3個空間來存儲元素,當存儲的元素超過3個時,系統會自動增大此數組的空間

    

    NSMutableArray *marray2 = [[NSMutableArray alloc] initWithCapacity:3];

    

    NSMutableArray *marray3 = [NSMutableArray arrayWithCapacity:3];

    

    

    

    新語法創建的是不可變數組 

    NSMutableArray *marray4 = @[s1,s2,s3];  //錯誤

    

    ---------------------2.添加元素--------------------------

    

    [marray2 addObject:s1];

    

    [marray2 addObject:s2];

    

    [marray2 addObject:s3];

    

    

    marray2中所有的元素全都添加到marray3

    

    [marray3 addObjectsFromArray:marray2];

    

    

    這是marray2添加到marray3中,marray3則是個二維數組

    

    [marray3 addObject:marray2];

    

    ---------------------3.插入元素--------------------------

    

    [marray2 insertObject:@"趙六" atIndex:0];

    

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

    

    [marray2 insertObject:@"zhaoliu" atIndex:0];  錯誤,數組越界

    

    

    

    ---------------------4.替換元素--------------------------

    

    [marray2 replaceObjectAtIndex:1 withObject:@"zhangfei"];

    

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

    

    

    

    ---------------------5.互換兩個元素的位置--------------------------

    

    [marray2 exchangeObjectAtIndex:3 withObjectAtIndex:2];

    

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

    

    

    

    ---------------------6.將另外一個數組的所有元素添加到當前數組--------------------------

    

    [marray3 addObjectsFromArray:marray2];

    

    

    

    ---------------------7.刪除元素--------------------------

    

    /*

     

     7.1根據下標刪除

     

     [marray2 removeObjectAtIndex:0];

     

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

     

     

     

     7.2根據對象刪除

     

     [marray2 removeObject:@"zhangfei"];

     

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

     

     

     

     7.3刪除最後一個元素

     

     [marray2 removeLastObject];

     

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

     

     

     

     7.4刪除所有元素

     

     [marray2 removeAllObjects];

     

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

     

     */

    

    

    

    ---------------------遍歷數組--------------------------

    

    1.普通遍歷

    

    /*

     

     for (int i=0; i<marray2.count; i++) {

     

     NSString *str = [marray2 objectAtIndex:i];

     

     // NSString *str2 = marray2[i];

     

     NSLog(@"%@",str);

     

     }

     

     */

    

    

    

    2.快速遍歷

    

    for (NSString *s in marray2) {

        

        NSLog(@"%@",s);

        

    }

    

    3.

    

    - (void)viewDidLoad

    

    {

        

        [super viewDidLoad];

        

        

        

        塊代碼 

        NSArray *array = @[@(1), @(2), @(3), @(4), @(5)];

        

        

        

        排序

        array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) {

            

            

            亂序=>一會升序,一會降序

             隨機

            arc4random_uniform(10) => 0~9之間的隨機數

            

            int seed = arc4random_uniform(2);

            

            if (seed) {

                

                return [num1 compare:num2];

                

            } else {

                

                return [num2 compare:num1];

                

            }

            

        }];

        

        

        

        NSLog(@"%@", array);

        

    }

    

    

    - (void)sortWith:(NSArray *)array

    

    {

        

        排序

        

        array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) {

            

            

            

            /**

             

             1 4 5 2

             

             4 1 5 2

             

             4 1 5 2

             

             5 4 1 2

             

             5 4 1 2

             

             5 4 2 1

             

             */

            

            NSLog(@"%@ %@", num1, num2);

            

            

            

            升序

            return [num1 compare:num2];            

            降序            

            return [num2 compare:num1];

            

        }];

                

        

        NSLog(@"%@", array);

        

    }

    

    

    - (void)arrayWith:(NSArray *)array

    

    {

        

        int i = 0;

        

        for (NSNumber *num in array) {

            

            NSLog(@"%@", num);

            

            

            

            if (i == 1) {

                

                break;

                

            }

            

            i++;

            

        }

        

        

        

        參數:對象,索引,是否中斷

        

        數組的塊方法遍歷的效率比for in

        

        [array enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) {

            

            NSLog(@"%@", obj);

            

            

            

            // idx == 1 退出循環

            

            if (idx == 1) {

                

                *stop = YES;

                

            }

            

        }];

        

    }

    

    

    

    

    NSDictonary

    

    

    /*________________________不可變字典(NSDictonary)___________________________*/

    

    

    

    1.字典的創建    

    NSArray *array1 = [NSArray arrayWithObjects:@"zhangsan",@"zhangfei", nil];

    

    NSArray *array2 = [NSArray arrayWithObjects:@"lisi",@"liping", nil];

    

    

    

    第一個元素:key:@“zhang”  value:array1

    

    第二個元素:key:@"li"     value:array2    

    NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@"zhang",array2,@"li", nil];

    

    NSUInteger count = [dic1 count];

    

    NSLog(@"count:%ld",count);

    

    

    

    NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:array1,@"zhang",array2,@"lisi", nil];

    

    

    

    創建字典時,初始化了一個元素    

    NSDictionary *dic3 = [NSDictionary dictionaryWithObject:array1 forKey:@"zhangsan"];

    

    

    

    2.獲取字典中元素的個數    

    NSUInteger count2 = [dic1 count];

    

    

    

    3.獲取字典中所有的key 

    NSArray *allkeys = [dic1 allKeys];

    

    NSLog(@"allkeys:%@",allkeys);

    

    

    

    4.獲取字典中所有的value    

    NSArray *allvalues = [dic1 allValues];

    

    NSLog(@"allvalues:%@",allvalues);

    

    

    

    5.通過key取得value    

    NSArray *array3 = [dic1 objectForKey:@"zhang"];

    

    NSLog(@"array3:%@",array3);

    

    

    

    /*________________________字典的新語法___________________________*/

    

    

    

    創建的語法:{"key1":"value1","key2":"value2"};    

    新語法創建字典    

    NSDictionary *dic4 = @{@"zhang":array1,@"li":array2};

    

    NSLog(@"dic4:%@",dic4);

    

    

    

    value的語法:字典["key"]    

    NSArray *array4 = dic4[@"zhang"];

    

    NSLog(@"array4:%@",array4);

    

    使用字典存儲一個工人的信息

    

    /*

     

     {

     

     "name": "zhangsan", 工人的姓名

     

     "age" : "22"        工人的年齡

     

     ...

     

     }

     

     */

    

    NSDictionary *worker = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"name",@"23",@"age", nil];

    

    

    

    

    

    /*________________________可變字典(NSMutableDictionary)___________________________*/

    

    

    1.創建一個可變的數組    

    NSMutableDictionary *mdic1 = [[NSMutableDictionary alloc] initWithCapacity:3];

    

    NSMutableDictionary *mdic2 = [NSMutableDictionary dictionaryWithCapacity:3];

    

    

    

    2.添加元素    

    [mdic1 setObject:array1 forKey:@"zhang"];

    

    [mdic1 setObject:array2 forKey:@"li"];

    

    

    

    將字典dic1中的元素添加到此字典中    

    [mdic1 addEntriesFromDictionary:dic1];  注意:相同的key是不能重複添加到字典中

    

    NSLog(@"mdic1:%@",mdic1);

    

    

    

    3.刪除    

    根據key刪除元素

    

    [mdic1 removeObjectForKey:@"zhang"];

    刪除多個元素

    

    [mdic1 removeObjectsForKeys:@[@"zhang",@"li"]];

    

    NSLog(@"mdic1:%@",mdic1);

    

    

    

    刪除所有的元素    

    [mdic1 removeAllObjects];

 

    1.第一種方式

    

    /*

     

     for (NSString *key in mdic1) {

     

     NSArray *names = [mdic1 objectForKey:key];

     

     NSLog(@"names:%@",names);

     

     }

     

     */

    

    

    

    2.第二種方式

    

    /*

     

     NSArray *keys = [mdic1 allKeys];

     

     for (int i=0; i<keys.count; i++) {

     

     NSString *key = [keys objectAtIndex:i];

     

     NSArray *names = [mdic1 objectForKey:key];

     

     NSLog(@"names:%@",names);

     

     }

     

     */

    

    

    

    3.第三種方式    

    獲取枚舉對象,枚舉對象中存儲的是字典裏所有的key    

    NSEnumerator *enumer = [mdic1 keyEnumerator];

    

        

    讓枚舉對象的遊標指向下一個對象    

    id key = [enumer nextObject];

    

    while (key != nil) {

        

                

        NSArray *names = [mdic1 objectForKey:key];

        

        NSLog(@"names:%@",names);

                        

        key = [enumer nextObject];

        

    }

    

    

    數組也可以使用枚舉對象遍歷

    

    /*

     

     NSArray *array = [NSArray array];

     

     NSEnumerator *enumer2 = [array objectEnumerator];

     

     */

    

       

    /*________________________字典排序___________________________*/

    

    

    

    NSDictionary *sortDic = @{

                              

                              @"zhangsan":@"50",

                              

                              @"lisi":@"90",

                              

                              @"wangwu":@"80",

                              

                              @"zhao6":@"60"

                              

                              };

    

    

    

    對字典中的value進行排序,參數obj1,obj2是字典中的value    

    返回值是排好序的key

    

    NSArray *sortedKeys = [sortDic keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        

        

        

        int v1 = [obj1 intValue];

        

        int v2 = [obj2 intValue];

        

        

        

        if (v1 > v2) {

            

            return NSOrderedDescending;

            

        } else if(v1 < v2) {

            

            return NSOrderedAscending;

            

        }

        

        

        

        return NSOrderedSame;

        

        

        

    }];

    

    

    

    for (NSString *name in sortedKeys) {

        

        NSString *score = [sortDic objectForKey:name];

        

        NSLog(@"name:%@,score:%@",name,score);

        

    }

    

    NSSet

    

    

    1.NSSet的創建

    

    NSString *s1 = @"zhangsan";

    

    NSString *s2 = @"lisi";

    

    NSSet *set1 = [[NSSet alloc] initWithObjects:s1,s2, nil];

    

    NSSet *set2 = [NSSet setWithObjects:s1,s2, nil];

    

    把數組array中的所有元素,存儲到set3

    NSSet *set3 = [NSSet setWithArray:array];

    

    

    

    2.NSSet轉成數組

    NSArray *array1 = [set1 allObjects];

    

    

    3.返回元素的個數

    NSUInteger count = [set1 count];

    

   

    

    4.從容器中隨機取出一個元素

    NSString *string1 = [set1 anyObject];

    

    

    5.判斷某一個對象是否在NSSet

    BOOL isContains = [set1 containsObject:@"lisi"];

    

     

    6.NSSet中不能重複存同一個對象       

    數組中是可以存取重複的對象

    

    NSString *str = @"jack";

    

    NSArray *array2 = [NSArray arrayWithObjects:str,str, nil];

    

    NSLog(@"%@",array2);

    

    

    

    NSSet中不能重複存儲相同的對象    

    NSSet *set4 = [NSSet setWithObjects:str,str, nil];

    

    NSLog(@"%@",set4);

    

    

    

    /*

     

     NSSetNSArray的區別

     

     1. 數組是有下標,NSSet是沒有下標的

     

     2. 數組是有序的,NSSet是無序的

     

     3. 數組是可以重複存儲同一個對象,NSSet反之,不能重複存儲對象

     

     */

    

    

    

   NSMutableSet

   NSNumber

    /*_______________________________NSNumber的使用___________________________________*/

    

     

    1.創建NSNumber(包裝基本數據類型)

    

    NSNumber *intNumber = [NSNumber numberWithInt:100];

    

    NSNumber *floatNumber = [NSNumber numberWithFloat:9.8f];

    

    NSNumber *longNumber = [NSNumber numberWithLong:145677766666];

    

    NSNumber *boolNumber = [NSNumber numberWithBool:YES];

    

    

    

    NSArray *array = @[intNumber,floatNumber,longNumber,boolNumber];

    

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

    

    

    

    2.解包   

    int intValue = [intNumber intValue];

    

    float floatValue = [floatNumber floatValue];

    

    long longValue = [longNumber longValue];

    

    BOOL boolValue = [boolNumber boolValue];

    

    

    

    3.新語法創建Number對象

    

    NSNumber *intNumber1 = @12;  //@"123";

    

    NSNumber *floatNumber1 = @12.0f;

    

    NSNumber *longValue1 = @19929292992;

    

    NSNumber *boolValue1 = @YES;

    

    NSNumber *charValue = @'a';

    

    

    /*_______________________________NSValue的使用___________________________________*/

    struct WXPoint {

        

        float x;

        

        float y;

        

    };

    

    

    

    1.創建NSValue(包裝結構體), NSValueNSNumber的父類

    

    注意:結構體不是對象

    

    NSRange rang = {100,6};

    

    NSRange封包

    

    NSValue *rangValue = [NSValue valueWithRange:rang];

    

    NSPoint封包

    

    NSValue *pointValue = [NSValue valueWithPoint:<#(NSPoint)#>];

    將自定義的結構體包裝成NSValue對象    

    struct WXPoint p = {50,100};    

    NSValue *pointValue = [NSValue value:&p withObjCType:@encode(struct WXPoint)];

        

    

    2.解包結構體    

    struct WXPoint p2;

    

    [pointValue getValue:&p2];   

    

    NSLog(@"x=%f,y=%f",p2.x,p2.y);

         

    3.NSNull對象    

    NSNull *n1 = [NSNull null];

    

    NSNull *n2 = [NSNull null];

    

    NSArray *arrayNull = @[n1,n2];

    

    NSLog(@"%@",arrayNull);

    

    

    

    for (id item in arrayNull) {

                        

        判斷數組中的對象是否爲一個NSNull對象,如果是,則過濾掉

        

        if (item == [NSNull null]) {

            

            continue;

            

        }

        

        

        

    }

    

NSDate:

    

    /*__________________________NSDate的使用_____________________________*/

    

    

    

    1.創建日期    

    NSDate *date1 = [NSDate date];  創建了一個當前的日期對象

    

    NSDate *date2 = [[NSDate alloc] init];

    

    NSLog(@"date2:%@",date2);

    

    

   

    在當前日期的基礎上累加一個數值,單位是秒    

    明天    

    NSDate *date3 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];

    

    NSLog(@"date3:%@",date3);

    

    

    

    昨天    

    NSDate *date4 = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];

    

    NSLog(@"date4:%@",date4);

    

    1970年上加一個數值,該數值是一個時間戳數值

    NSDate *date1970 = [NSDate dateWithTimeIntervalSince1970:0];

    

    NSLog(@"date1970:%@",date1970);

    

    

    2.獲取日期的時間戳    

    NSTimeInterval time1970 = [date1 timeIntervalSince1970];

    

    NSLog(@"time1970:%f",time1970);

    

    

    

    取得日期對象date3到當前日期時間的數值差    

    NSTimeInterval timeNow = [date3 timeIntervalSinceNow];

    

    NSLog(@"timeNow:%f",timeNow);

    

      

    

    3.日期的比較    

    (1)通過日期對象的compare方法進行比較

    

    NSComparisonResult result = [date3 compare:date1];

    

    if (result == NSOrderedDescending) {

        

        NSLog(@"date3 > date1");

        

    }

    

    (2)通過比較時間戳

    

    if ([date3 timeIntervalSince1970] > [date1 timeIntervalSince1970]) {

        

        NSLog(@"date3 > date1");

        

    }

    

    

    

    

    

    /*__________________________NSDateFormatter格式化日期_____________________________*/

    

    

    

    1.日期對象格式化爲字符串: 2013-07-29 15:20:59  20130729

    

     日期對象 --> 字符串    

    NSDate *nowDate = [NSDate date];

    

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

    

    設置日期的格式    

    [dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss"];

    

    設置時區    

    NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"America/New_York"];

    

    [dateFormatter setTimeZone:timezone];

            

    stringFromDate:將日期對象格式化爲字符串    

    NSString *datestring = [dateFormatter stringFromDate:nowDate];

    

    NSLog(@"格式化之後:%@",datestring);

            

    2.將字符串格式化成日期對象

    

    字符串 ——>日期對象    

    NSString *string = @"20130729 16:56:05";

    

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

    

    [dateFormatter2 setDateFormat:@"yyyyMMdd HH:mm:ss"];

    

    dateFromString: 將字符串格式化成日期對象    

    NSDate *formatDate = [dateFormatter2 dateFromString:string];

    

    NSLog(@"%@",formatDate);

              

    

    獲取到所有時區的名稱    

    NSArray *zoneNames = [NSTimeZone knownTimeZoneNames];

    

    for (NSString *name in zoneNames) {

        

        NSLog(@"%@",name);

        

    }

        

    

    /*__________________________捕捉異常_____________________________*/

    

    創建一個空數組   

    NSArray *arr = [NSArray array];

    

    

    

    @try有可能出異常的代碼塊

        

            數組越界異常        

        [arr objectAtIndex:5];

        

    }

    

    @catch (NSException *exception) {

        

        如果捕捉到錯誤,則會執行此處的代碼       

        NSLog(@"錯誤:%@",exception);

        

    }

    

    @finally@finally是可選的

        

        不管有沒有捕捉到異常,此處代碼都會執行

        

        NSLog(@"@finally");

        

    }

            

    判斷wearNeat方法是否在Student類中定義,如果定義了,才調用

    

    if ([stu respondsToSelector:@selector(wearNeat)]) {

        

        [stu wearNeat];

        

    }

    

    

    歸檔:數據存儲

    /*____________________________第一種形式________________________________*/

        

    /****************對象歸檔********************/

    

    對象------>文件    

        

    /*

     

     NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"中文", nil];

     

     歸檔保存的文件路徑     

     NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.arc"];

     

     

     

     歸檔對象    

     BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];

     

     

     

     if (success) {

     

     NSLog(@"歸檔成功");

     

     }

     

     */

    

    

    

    

    

    /****************解歸檔********************/    

    /*

     

     文件----->對象     

     歸檔保存的文件路徑     

     NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.arc"];

          

     解歸檔     

     NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

             

     for (NSString *s in array) {

     

     NSLog(@"%@",s);

     

     }

     

     */

        

    

    /*____________________________第二種形式________________________________*/

    

    

    

    /*    

     NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"中文", nil];     

     NSMutableData用於存儲歸檔對象中的數據     

     NSMutableData *data = [NSMutableData data];

     

     創建歸檔對象    

     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

           

     編碼數據和對象

     [archiver encodeObject:array forKey:@"array"];

     

     [archiver encodeInt:100 forKey:@"scope"];

     

     [archiver encodeObject:@"jack" forKey:@"name"];

     

     完成歸檔,將歸檔數據填充至data中,此時data中已經存儲了歸檔對象的數據

     

     [archiver finishEncoding];

     

     [archiver release];

     

     

     

     NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"ar.text"];

     

     將歸檔數據寫入文件    

     BOOL success = [data writeToFile:filePath atomically:YES];

     

     if (success) {

     

     NSLog(@"arichiver success");

     

     }

         

     */

    

    

    

    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"ar.text"];

    

    讀取歸檔數據    

    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];

        

    創建解歸檔對象,對data中的數據進行解歸檔    

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];   

    

    解歸檔,還原數據    

    NSArray *array = [unarchiver decodeObjectForKey:@"array"];

    

    int scope = [unarchiver decodeIntForKey:@"scope"];

    

    NSString *name = [unarchiver decodeObjectForKey:@"name"];

       

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

    

    NSLog(@"scope=%d",scope);

    

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

    

}

 

單例設計模式

獲取單例對象的類方法

+ (AdressBook *)shareInstance {

    

    

    

    if (instacne == nil) {

        

        instacne = [[AdressBook alloc] init];

        

    }

    

    return instacne;    

}

 

限制方法,限制這個類只能創建一個對象

+ (id)allocWithZone:(NSZone *)zone {

    

    if (instacne == nil) {

        

        instacne = [super allocWithZone:zone];

        

    }

    

    return instacne;

    

}

 

- (id)copyWithZone:(NSZone *)zone {

    

    return self;

    

}

 

- (id)retain {

    

    return instacne;

    

}

 

- (oneway void)release {

    

}

 

- (id)autorelease {

    

    return self;

    

}

 

- (NSUInteger)retainCount {

    

    return UINT_MAX;

    

}

 

沙盒路徑:

1Documents目錄:您應該將所有de應用程序數據文件寫入到這個目錄下。這個目錄用於存儲用戶數據或其它應該定期備份的信息。

2AppName.app目錄:這是應用程序的程序包目錄,包含應用程序的本身。由於應用程序必須經過簽名,所以您在運行時不能對這個目錄中的內容進行修改,否則可能會使應用程序無法啓動。

3Library 目錄:這個目錄下有兩個子目錄:Caches Preferences

Preferences 目錄:包含應用程序的偏好設置文件。您不應該直接創建偏好設置文件,而是應該使用NSUserDefaults類來取得和設置應用程序的偏好.

Caches 目錄:用於存放應用程序專用的支持文件,保存應用程序再次啓動過程中需要的信息。

4tmp目錄:這個目錄用於存放臨時文件,保存應用程序再次啓動過程中不需要的信息。

 

獲取這些目錄路徑的方法:

1,獲取家目錄路徑的函數:

NSString *homeDir = NSHomeDirectory();

 

2,獲取Documents目錄路徑的方法:

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

NSString *docDir = [paths objectAtIndex:0];

 

3,獲取Caches目錄路徑的方法:

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

NSString *cachesDir = [paths objectAtIndex:0];

 

4,獲取tmp目錄路徑的方法:

NSString *tmpDir = NSTemporaryDirectory();

 

5,獲取應用程序程序包中資源文件路徑的方法:

例如獲取程序包中一個圖片資源(apple.png)路徑的方法:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];

UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

 

做推送:

https://itunes.apple.com/tw/app/apn-tester-free/id626590577?l=zh&mt=12

 

文件路徑處理:

演示路徑

NSString *path = @"/Users/apple/file.text";

NSLog(@"演示路徑:%@",path);

 

1.返回路徑的組成部分

NSArray *array = [path pathComponents];

NSLog(@"pathComponents:%@",array);

 

2.路徑的最後組成部分

NSString *lastComponent = [path lastPathComponent];

NSLog(@"lastComponent:%@",lastComponent);

 

3.追加子路徑

NSString *newPath1 = [path stringByAppendingString:@"/appFile.text"];

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

 

NSString *newPath2 = [path stringByAppendingPathComponent:@"appFile.text"];

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

 

4.刪除最後的組成部分

NSString *deleteLast = [path stringByDeletingLastPathComponent];

NSLog(@"deleteLast:%@",deleteLast);

 

5.刪除擴展名

NSString *deleteExtension = [path stringByDeletingPathExtension];

NSLog(@"deleteExtension:%@",deleteExtension);

 

6.獲取路徑最後部分的擴展名

NSString *extension = [path pathExtension];

NSLog(@"extension:%@",extension);

 

7.追加擴展名

NSString *appendExt = [path stringByAppendingPathExtension:@"jpg"];

NSLog(@"appendExt:%@",appendExt);

 

NSString ---> NSData

NSString *s = @"tsdfsdfsdfsdf";

NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];

 

NSData -———> NSString

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

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

 

NSMutableData 可變的Data對象,可以追加數據

文件操作:

 

NSString *homePath = NSHomeDirectory();

 

源文件路徑

NSString *srcPath = [homePath stringByAppendingPathComponent:@"06 第六課 文件管理.pdf"];

目標文件路徑

NSString *targetPath = [homePath stringByAppendingPathComponent:@"Documents/06第六課文件管理.pdf"];

 

/*

 

 注意:使用NSFileHandle只能讀寫已經存在的文件,不能創建文件

 

 使用NSFileManager創建文件

 

 */

 

NSFileManager *fileManager = [NSFileManager defaultManager];

 

創建目標文件

BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil];

 

if (success) {

    

    NSLog(@"目標文件創建成功!");

    

}

 

創建用於讀取文件的NSFileHandle對象

NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];

 

創建用於寫入的NSFileHandle對象

NSFileHandle *wrteHandle = [NSFileHandle fileHandleForWritingAtPath:targetPath];

 

從當前偏移量讀到文件的末尾,偏移量默認是起始位置

NSData *data = [readHandle readDataToEndOfFile];

NSData *data = [readHandle availableData];

 

將數據寫入目標文件

[wrteHandle writeData:data];

 

關閉文件

[readHandle closeFile];

[wrteHandle closeFile];

 

/*___________________________1.創建文件_____________________________*/

 

/*

 

 獲取當前app的沙盒根目錄

 NSString *homePath = NSHomeDirectory();

 

 追加子路徑

 NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 NSString *string = @"無限互聯";

 

 NSString轉成NSData對象

 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 

 NSFileManager 不能使用alloc創建,這個類設計爲單實例

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

 NSFileManager 只能通過類方法defaultManager 創建 

 NSFileManager *fileManager = [NSFileManager defaultManager];

 

 

 根據路徑filePath創建對應的文件,注意:只能創建文件,不能創建目錄(文件夾)

 BOOL success = [fileManager createFileAtPath:filePath

 contents:data

 attributes:nil];

 

 if (success) {

 

 NSLog(@"文件創建成功");

 

 } else {

 

 NSLog(@"文件創建失敗");

 

 }

  

 

 創建文件夾

 NSString *filePath2 = [homePath stringByAppendingPathComponent:@"Documents/demo"];

 

 NSError *error;

 

 BOOL suucces2 = [fileManager createDirectoryAtPath:filePath2

 

 withIntermediateDirectories:YES

 

 attributes:nil

 

 error:&error];

 

 if (!suucces2) {

 

 NSLog(@"創建失敗:%@",error);

 

 }

 

 */

 

/*___________________________2.讀取文件_____________________________*/

獲取當前app的沙盒根目錄

NSString *homePath = NSHomeDirectory();

 

追加子路徑

NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 

NSFileManager *fileManager = [NSFileManager defaultManager];

 

根據路徑讀取文件中的數據

NSData *data = [fileManager contentsAtPath:filePath];

 

NSData NSString

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"%@",string);

 

/*___________________________3.移動(剪切)文件_____________________________*/

/*

 

 獲取當前app的沙盒根目錄

 NSString *homePath = NSHomeDirectory();

 

 源路徑 

 NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 

 

 目標路徑

 NSString *tagetPath = [homePath stringByAppendingPathComponent:@"Documents/demo/file2.text"]; 

 NSFileManager *fileManager = [NSFileManager defaultManager];

 

 

 moveItemAtPath: 移動文件

 BOOL success = [fileManager moveItemAtPath:filePath toPath:tagetPath error:nil];

 

 if (!success) {

 

 NSLog(@"移動失敗!!");

 

 }

 

 */

 

/*___________________________4.複製文件_____________________________*/

/*

 

 獲取當前app的沙盒根目錄

 NSString *homePath = NSHomeDirectory();

   

 源路徑

 NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/demo/file3.text"];

 

 

 

 目標路徑 

 NSString *tagetPath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 NSFileManager *fileManager = [NSFileManager defaultManager];

 

 

 copyItemAtPath: 將源文件複製到目標路徑

 BOOL success = [fileManager copyItemAtPath:filePath toPath:tagetPath error:nil];

 

 if (!success) {

 

 NSLog(@"複製失敗!!");

 

 }

 

 */

 

/*___________________________5.刪除文件_____________________________*/

 

/*

 

 獲取當前app的沙盒根目錄

 NSString *homePath = NSHomeDirectory();

 

 源路徑

 NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/demo/file3.text"]; 

 NSFileManager *fileManager = [NSFileManager defaultManager];

 

 判斷文件是否存在

 BOOL fileExist = [fileManager fileExistsAtPath:filePath];

 

 if (fileExist) {

 

 removeItemAtPath:刪除文件

 

 BOOL success = [fileManager removeItemAtPath:filePath error:nil];

 

 if (success) {

 

 NSLog(@"刪除成功!!");

 

 }

 

 }

 

 */

 

/*___________________________6.獲取文件的屬性_____________________________*/

 

/*

 

 NSFileManager *fileManager = [NSFileManager defaultManager];

 

 NSString *homePath = NSHomeDirectory();

 

 目標路徑

 NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 

 

 獲取到文件的屬性信息,文件的屬性信息存儲fileAttr字典中

 NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:filePath error:nil]; 

 NSLog(@"%@",fileAttr);

 

 從字典中通過key:NSFileSize獲取到文件大小

 NSNumber *filesize = [fileAttr objectForKey:NSFileSize];

 long sizeValue = [filesize longValue];

 NSLog(@"文件大小:%ld",sizeValue);

  

 如下讀取文件的大小,不可取,因爲將文件中的數據全都讀到內存中,文件大時,太佔用內存了

 NSData *data = [fileManager contentsAtPath:filePath];

 NSInteger len = data.length;

 

 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

 

 */

 

 

UITableView的一些使用方法:

_tableView.dataSource = self;

_tableView.delegate = self;

_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

 

/**

 

 UITableViewStylePlain,     平板的格式

 

 UITableViewStyleGrouped    分組的格式

 

 */

 

設置行高

self.tableView.rowHeight = 120;

 

分隔線

self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

 

headView,放在tableView最頂部的視圖,通常用來放圖片輪播器

UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 130)];

head.backgroundColor = [UIColor blueColor];

self.tableView.tableHeaderView = head;

 

footerView,通常做上拉刷新

UIView *foot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

foot.backgroundColor = [UIColor redColor];

self.tableView.tableFooterView = foot;

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章