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

原文地址:https://www.cnblogs.com/langtianya/p/4018728.html