OC学习总结(一)
知识要点
1、 类(interface)
》头文件格式.h
@interface class-name : super-class-name <protocol-name,...>{
@private
instance variable
...
@public
...
@protected(default)
...
}
@property ... //点语法中可以方便使用
//xcode4.4以后property关键字实现了三部分工作:成员变量的定义如_name(默认为private),property和synthesize的功能
//构造方法的命名约定(以Person类为例):类方法personWith开头,实例方法initWith开头
//+开头的类方法
//-开头的实例方法
@end
》实现文件.m(.mm)
@implementation class-name
@synthesize ... //点语法中可以方便使用
//实现方法
...
@end
2、 分类(Category)
》头文件格式.h
@interface class-name (category-name)
//+开头的类方法
//-开头的实例方法
@end
》实现文件.m(.mm)
@implementation class-name (category-name)
//实现方法
...
@end
3、 协议(Protocol)
》头文件格式.h
@protocol protocol-name
//协议方法
...
@end
4、 扩展(Extension)
》声明和实现都在.m文件中
》格式类似于无名Category
@interface class-name ()
@end
》实现在原有类的implementation中
》相当于私有方法,类内部才可用
5、 委托(Delegate)
》协议的一大特色,代理模式
》协议FindHouse的定义
@protocol FindHouse
- (void) findHouse;
@end
》代理中介Agent
@interface Agent : NSObject <FindHouse>
- (void) findHouse;
@end
》甲方Person
@interface Person : NSObject{
id<FindHouse> delegate; //实现了FindHouse协议的对象都可以作为代理
}
+ (id) personWithDelegate:(id<FindHouse>)pDelegate; //注入代理
- (void) startToFindHouse;
@end
6、 Foundation框架
》NSNumber(涉及到基本数据类型和对象的相互转化,包装和拆包)
包装[Number numberWithInt:age]
拆包[number intValue]
》NSString(字符串的初始化、拼接、查找和比较)
字面量语法 NSString *str = @"hello oc"
长度[str length]
子串substringFrom, substringTo, substringWithRange
比较isEqualToString, compare, caseInsensitiveCompare
拆分字符串 componentsSeparatedByString
数组拼接字符串componentsJoinedByString
字符串拼接stringWithFormat
查找字符串hasPrefix, hasSuffix, containsString, rangeOfString
》NSArray(数组中只能存放对象,包括可变NSMutableArray和不可变数组)
创建arrayWithObjects, arrayWithArray
长度[arr count]
查找indexOfObject
可变数组addObject
》NSSet(无序列表,只能存放对象,分类可变NSMutableSet和不可变集合,自动去除重复对象)
创建setWithObjects
增加setByAddingObject(返回新对象)
可变集合NSMutableSet
子集判断intersectsSet
交集intersectSet
差集minusSet
》NSDictionary(字典为键值对,键值都必须是对象,而且都不能为nil,如果值为空时可采用NSNull)
创建dictionaryWithObjectsAndKeys
取值objectForKey
可变字典 setValue: forKey
删除removeObjectForKey