oc(object-c)知識匯總/總結/區別對比(持續更新)


1、判斷某個類是否實現了某方法: 

A *a =[[A alloc] autorelease]; 

if([a respondsToSelector:@selector(methodName)])
{
//do something
}else{

//do other something
}

2、判斷某個類是否實現了某協議: 

A *a =[[A alloc] autorelease]; 

if([a conformsToProtocol:@protocol(protocolName)]) { //do something }else{ //do other something }

3、new與alloc]init]區別:new其實就是等價於alloc]init]

4、在頭文件聲明私有方法:用Categor(分類)

5、類似java的toString方法:

-(NSString *)description{

return you string }

6、判斷一個對象是否為空

self=[super init];
if(self=[super init]){//或者 if(self)
}

 7、self的兩種狀態:如果是動態方法調用就代表對象,靜態方法調用就代表類。

8、在接口體內的變量默認是保護的(protected)

@interface Student:NSObjedt{
//protected
int age; } //這里的默認是public @end

9、對變量生成getter和setter方法的歷史演變

最初是手動編寫get和set方法,后來有了@property之后可以用@synthesize代替,只要在m文件添加了”@synthesize 變量名“ 那么默認會去訪問與該變量名同名的變量,

如果找不到同名的變量,會自動生成一個私有的同名變量。在xcode4.5以后的版本就可以省略@synchesize了,可以用“_變量名” 訪問同名變量,其作用等同於@synchesize

10、

創建NSRange變量的三種方式:

1>  NSRange range;

range.location=1; range.lenght=1; 2> NSRange range={1,1};//或者NSRange range={.location=1,.length=1}; 3> NSRange range=NSMakeRange(1,1);

11、NSPoint與CGPoint的區別:其實沒區別,NSPoint只是CGPoint的別名,CGPoint是一個結構體.相關代碼:

struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef CGPoint NSPoint;

CGSize/NSSize、CGRect/NSRect的區別同上。

12、幾個可能容易混淆的類/結構體:

1>  NSRange 表示范圍,一般用來指定一個字符串,集合等的子集范圍。location表示從哪里開始,lenght表示從開始點到結束點的長度。創建方法看上面。其中有一種

NSRange range=NSMakeRange(1,1);

2> CGPoint/NSPoint 表示平面上的一個點。x表示x軸,y表示y軸,創建方式:

CGPoint p=CGPointMake(1,1);

 NSPoint p=NSMakePoint(1,1);

3> CGSize/NSSize 表示寬度和高度,比如一個矩形的寬高,屬性有width height。創建方式:

CGSize s=CGSizeMake(1,1);

NSSize s=NSMakeSize(1,1);

4> CGRect/NSRect 表示一個控件的左上角坐標和控件的寬和高,是2>和3>的結合體,看定義:

struct CGRect {
CGPoint origin;
CGSize size;
}

 

創建方式 

  CGRect r=CGRectMake(1,1,1,1);
   NSRect r=NSMakeRect(1,1,1,1);
還有其他創建方式,不討論

13、NSString的幾/7種創建方式:
  //1、這種方式創建,不需要釋放內存
  NSString*str1=@"A String";

  //2、
   NSString*str2=[[NSString alloc]init];   str2=@"B String";   [str2 release];    //3、   SString*str3=[[NSString alloc]initWithString:@"C string!"];   [str3 release];      //4、靜態方法創建對象,不需要管理內存   str4=[NSString stringWithString:@"c string!"];  
  //5、   NSString *str5 = [[NSString alloc] initWithUTF8String:"D string!"];   [str5 release];   //6、    NSString *str6 = [[NSString alloc] initWithFormat:@"my age is %i and height is %.2f",28,1.65f];   [str6 release];
    //7、

char *cString =“c字符串”;

NSString *str7 =[[NSString alloc]initWithCString:cString encoding:NSUTF8StringEncoding];

[str7release];

另外還有很多種從其他類轉化成字符串的方法,比如

NSStringFromxxx系列方法和[NSString stringWithxxx ]系列方法

 14、字符串操作:

字符串截取

//從form到字符串末尾,包括form的位置
- (NSString *)substringFromIndex:(NSUInteger)from;
//從字符串開始到to位置,不包括to位置 - (NSString *)substringToIndex:(NSUInteger)to;
//截取range范圍內的字符串 - (NSString *)substringWithRange:(NSRange)range;
//利用給定的分隔符截取分隔符分開的子字符串數組
- (NSArray *)componentsSeparatedByString:(NSString *)separator;

比較字符串

- (BOOL)isEqualToString:(NSString *)aString;

//是否以。。結尾

- (BOOL)hasSuffix:(NSString *)aString;

判斷字符串以..開頭

- (BOOL)hasPrefix:(NSString *)aString;

比較字符串

//下列方法會逐個字符的比較,返回的NSComparisonResult包含升序,相等,降序三個值(NSOrderedAscending NSOrderedSame NSOrderedDescending)

- (NSComparisonResult)compare:(NSString *)string;

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange;

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange locale:(id)locale; /

//忽略大小寫比較

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;

大小寫操作:

- (NSString *)uppercaseStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);//全部轉成大小

- (NSString *)lowercaseStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);//全部轉成小寫

- (NSString *)capitalizedStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);//僅首字母轉大小

 

類似java的indexOf方法:

- (NSRange)rangeOfString:(NSString *)aString;//如果包含則返回aString的位置,否則返回location為-1,length為0

NSString *string=@“abcdefg”;

NSRange range=[string rangeOfString:@“bcd”];
if(range.location==NSNotFound){
//do something
}else{
NSLog(@“找到的范圍:%@”,NSStringFromRange(range));
}

 

//下面的mask是指定從哪里開始搜索即從頭向尾還是從尾到頭的順序搜索

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;

NSString *string=@“abcdefg”;
//從尾到頭的順序搜索
NSRange range=[string rangeOfString:@“bcd” options:NSBackwardsSearch];
if(range.location==NSNotFound){
//do something
}else{
NSLog(@“找到的范圍:%@”,NSStringFromRange(range));
}

 

//下面的searchRange是指定要搜索的范圍

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale NS_AVAILABLE(10_5, 2_0);

 

更多字符串操作參考官方文檔

 

15、讓數組的每個元素都調用同一個方法

NSArray  *arr=[NSArray arrayWithObjects:obj1,obj2,obj3,nil];

[arr makeObjectsPerformSelector:@selector(methodName)];

 

16、數組操作

//順序遍歷數組,
NSArray *array=[NSArray arrayWithObjects:obj1,obj2,obj3,nil];
NSEnumerator *enumerator=[array objectEnumerator];
id *obj=nil;
while(obj=[enuerator nextObject]){
//do something
}

//逆序逆向遍歷數組
NSArray *array=[NSArray arrayWithObjects:obj1,obj2,obj3,nil];
NSEnumerator *enumerator=[array reverseObjectEnumerator];
id *obj=nil;
while(obj=[enuerator nextObject]){
//do something
}
//獲取沒有被遍歷過的數組元素
NSArray *array=[enumerator allObjects];

//block遍歷數組

NSArray *arr=[NSArray arrayWithObjects:@""nil];

    [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        NSLog(obj);

        if (idx==3) {

            stop=YES;

        }

    }];

 
         

//利用block進行排序

    NSArray *arr=[NSArray arrayWithObjects:@"", nil];

    [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        if(obj1.xx1 campare obj2.xx1==NSOrderedSame){

            return [obj1.xx2 campare obj2.xx2 ];

        }}];
 
//利用描述器進行數組排序

NSArray *arr=[NSArray arrayWithObject:person1,person2,nil];

//先名字排序
NSSortDescriptor *desc1=[NSSortDescriptor sortDescriptorWithKey:@“name ascending:YES];
//再年齡排序

NSSortDescriptor *desc2=[NSSortDescriptor sortDescriptorWithKey:@“age“ ascending:YES];

//再….排序

NSArray *descArr=[NSArray arrayWithObjects: desc1, desc2,nil];
NSArray sortArr=[arr sortedArrayUsingDescriptors:descs];
 

 17、字典操作:

//遍歷字典
//快速遍歷方式
for(NSString *key in dictionary){
id *value=[dictionary objectForKey:key];
}
//迭代器遍歷
-(NSEnumerator*)keyEnumerator
-(NSEnumerator*)objectEnumerator
//block遍歷
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key,id object,BOOL stop){
//do something
}

18、

將基本類型char short int long longlong float double、bool integer unsignedInteger封裝成對象

或者將對象解包成char short int long longlong float double、bool integer unsignedInteger基本類型

//以int為例,其他類似,具體參考官方穩定
NSNumber *number=[NSNumber numberWithInt:11
];
int myInt=[number intValue
];

 

19、

 

//將NSPoint、NSSize、NSRect等結構體包裝成對象,再解包成結構體,以NSPoint為例

1、

NSPoint point=NSMakePoint{1,1};

NSValue * value=[NSValue valueWithPoint:point;

NSPoint point2=[value pointValue];


2、

CGPoint point={1,1};

    char *type=@encode(CGPoint);  

    NSValue * value=[NSValue value:&point withObjCType:type];

    CGPoint point2;

    [value getValue:&point2];

 20、時間/日期操作

//格式化時間/日期
NSDate *date=[NSDate date];
NSDateFormatter *formatter=[[NSDateformatter alloc]init];
formatter.dateFormat=@“yyyy-MM-dd hh:mm:ss”;//如果是HH表示24進制,hh是12進制,比如晚上11點如果是24進制顯示的時23,12進制是11
NSString *dateString=[formatter stringFromDate:date];
[formatter release];

//日期與字符串互轉
NSDateFormatter *formatter=[[NSDateformatter alloc]init]; formatter.dateFormat=@“yyyy-MM-dd hh:mm:ss”;//如果是HH表示24進制,hh是12進制,比如晚上11點如果是24進制顯示的時23,12進制是11
NSString *dateString=[formatter stringFromDate:date];
NSDate *date=[formatter DateFromString:@"2014-11-11 11:11:11"];

[formatter release];
//返回當地時間
NSDate *date=[NSDate date];
NSDateFormatter *formatter=[[NSDateformatter alloc]init]; formatter.dateFormat=@“yyyy-MM-dd hh:mm:ss”;//如果是HH表示24進制,hh是12進制,比如晚上11點如果是24進制顯示的時23,12進制是11
formatter.locale=[[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] autorelease]; NSString *dateString=[formatter stringFromDate:date]; [formatter release];

 

 


21、object的反射實現

//判斷某個對象是否屬於某個類或其子類的對象
id stu=[[[Student alloc]init]autorelease];
[stu isKindOfClass:[Student class]];
//判斷某個對象是否屬某個類子類的對象(不包括其子類的對象)
//定時執行某方法,這里是2秒后執行
[stu performSelector:@selector(test@:) withObject:@“abc” afterDelay:2];

//object-c的反射
Class class=NSClassFromString(@”Student“);
Student *stu=[[class alloc] init]

//獲Class的類名字符串表示
Class class=[Student class];
NSString *className=NSStringFromClass(class);

//通過反射調用方法
SEL selector=NSSelectorFromString(@“method name”);
[stu performSelector:selector withObject:@“Mike”];
//將方法變成字符串
NSStringFromSelector(@selector(mehtodName)

 22、設置UIView的四個角的弧度

self.contentView.layer.cornerRadius=10;

 23、顏色/背景顏色

+ (UIColor *)blackColor;      // 0.0 white 
+ (UIColor *)darkGrayColor;   // 0.333 white 
+ (UIColor *)lightGrayColor;  // 0.667 white 
+ (UIColor *)whiteColor;      // 1.0 white 
+ (UIColor *)grayColor;       // 0.5 white 
+ (UIColor *)redColor;        // 1.0, 0.0, 0.0 RGB 
+ (UIColor *)greenColor;      // 0.0, 1.0, 0.0 RGB 
+ (UIColor *)blueColor;       // 0.0, 0.0, 1.0 RGB 
+ (UIColor *)cyanColor;       // 0.0, 1.0, 1.0 RGB 
+ (UIColor *)yellowColor;     // 1.0, 1.0, 0.0 RGB 
+ (UIColor *)magentaColor;    // 1.0, 0.0, 1.0 RGB 品紅
+ (UIColor *)orangeColor;     // 1.0, 0.5, 0.0 RGB 橙色
+ (UIColor *)purpleColor;     // 0.5, 0.0, 0.5 RGB 紫色
+ (UIColor *)brownColor;      // 0.6, 0.4, 0.2 RGB 棕色
+ (UIColor *)clearColor;      // 0.0 white, 0.0 alpha 透明度和灰度都是0

要清除uiview的背景顏色:view.backgroundColor=[UIColor clearColor];

24、設置UILable自動換行:

UILable label=[[UILable alloc] init];
label.numberOfLines=0;//自動換行
label.textColor=[UIColor whiteColor];
label.textAlignment=NSTextAlignmentCenter//設置文字的排列方式

 25、UIApplication的一些功能

//設置ios應用在手機桌面顯示的圖標右上角顯示數字:
[UIApplication sharedApplication].applicationIconBadgeNumber=10;//10就是那個數字,可以隨意改成其他數字
//判斷程序運行狀態//2.0以后
//UIApplicationStateActive激活狀態
//UIApplicationStateInactive不激活的狀態
//UIApplicationStateBackground//進入后台
([UIApplication sharedApplication].applicationState==UIApplicationStateInactive){
}
//阻止屏幕變暗進入休眠狀態2.0
[UIApplication sharedApplication].iconTimerDisabled=YES;
//顯示手機網絡狀態2.0
[UIApplication sharedApplication].networkActivityingDiscatorVisible=YES;
//在map地圖上顯示一個地址
NSSting *address=@”xxxx“;
address=[address stringByAddingPercentEscapesUsingEncoding:NSASCiiStringEncoding];
NSString * url=[NSString stringWithFormat:”http://maps.google.com/maps?q=%@“,url];
[UIApplication sharedApplication].openURL:[NSURL URLWithString:url];
//打開一個網址
[UIApplication sharedApplication].openURL:[NSURL URLWithString:@“sms:http://xx.com"];
//打電話到指定號碼功能
[UIApplication sharedApplication].openURL:[NSURL URLWithString:@“tel:15007553054”];
//發送短信功能 
[UIApplication sharedApplication].openURL:[NSURL URLWithString:@“sms:15007553054”];
//發送電子郵件
http://www.cnblogs.com/langtianya/p/4052882.html

 

   26、 移除棧定的視圖

    [self.navigationController popViewControllerAnimated:YES];

 

  視圖控制器自己把自己從父視圖控制器中移除

//Removes the receiver from its parent in the view controller hierarchy.

[self.navigationController removeFromParentViewController];

 子視圖父視圖窗口中斷開鏈接並從響應鏈中刪除

[self.view removeFromSuperview];

 

27、刷新UITableview的界面

 //刷新界面
/
/帶動畫刪除

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

.........此處省略一萬字^ _ ^

 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];

//重新向數據源請求數據,重新渲染所有的cell
//        [tableView reloadData];

 

 

28、 NSDictionary、 NSMutableDictionary、 NSData、 NSMutableData、NSArray、 NSMutableArray、 NSString、  NSMutableString等類擁有相同/相似方法名詞的方法:

//像- (NSString *)description;、- (BOOL)isEqual:(id)object;等從父類繼承的方法就不說了,這里說的時並不是從父類繼承的,但是卻有相同名詞的方法

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; // the atomically flag is ignored if url of a type 

+ (NSDictionary *)xxxWithContentsOfFile:(NSString *)path;
+ (NSDictionary *)xxxWithContentsOfURL:(NSURL *)url;
- (NSDictionary *)initWithContentsOfFile:(NSString *)path;
- (NSDictionary *)initWithContentsOfURL:(NSURL *)url;

//相同性更多的是NSDictionary家族與NSArray家族,除了上面的方法外還有:

- (void)removeAllObjects;

 29、持久化數據有5種方式:

     1MXL屬性列表歸檔(plist文件)  2 NSKeyedArchiver歸檔  3 Preference 偏好設置歸檔  4 SQLite3存儲  5 Core data歸檔

30、常用16種視圖切換動畫

效果和源碼下載地址:http://code4app.com/ios/%E5%B8%B8%E7%94%A816%E7%A7%8D%E8%A7%86%E5%9B%BE%E5%88%87%E6%8D%A2%E5%8A%A8%E7%94%BB/500903b76803fa2f43000000

 

 31 、隱藏Status bar(狀態欄)、NavigationBar(導航欄)、tabBarController(標簽欄) (2011-12-17 16:08:04)


標簽: ios    分類: iOS開發
 
隱藏Status bar(狀態欄)
[[UIApplication sharedApplication] setStatusBarHidden:YES];
隱藏NavigationBar(導航欄)
[self.navigationController setNavigationBarHidden:YES animated:YES];
隱藏tabBarController(標簽欄)   尺寸改成大於480就OK。
[self.tabBarController.view setFrame:CGRectMake(0, 0, 320, 520)];

 

轉載注明原文:http://www.cnblogs.com/langtianya/p/4018728.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM