Chapter 3 Allocating and Initializing Objects
1.NSObject的alloc方法,动态地给对象分配足够的内存来容纳其实例变量,该方法将对象的isa变量初始化为实力对象的类对象,其他变量则设置为0
2.初始化方法应该返回id对象
3.在自定义初始化方法中,应该调用指定初始化方法(designated initializer),指定初始化方法必须要调用父类的指定初始化方法
4.在初始化方法中指定实例变量,应该直接赋值,而不是使用存取方法
5.在初始化方法的结尾返回self
6.指定初始化方法是每个类中保证继承变量被初始化的方法,指定初始化方法必须调用其父类的指定初始化方法
+ (Soloist *)soloist {
static Soloist *instance = nil;
if ( instance == nil ) {
instance = [[self alloc] init];
}
return instance;
}singleton实例的定义
Chapter 4 Protocols
1.协议是一组与类定义无关的方法的集合
2.正式协议
@protocol MyProtocol
- (void)requiredMethod;
@optional
- (void)anOptionalMethod;
- (void)anotherOptionalMethod;
@required
- (void)anotherRequiredMethod;
@end3.非正式协议通常声明为NSObject的categories,但是不需要相应的实现(与category不同)。遵守该协议的对象,在接口文件中再次声明协议方法,并定义其具体实现
@interface NSObject ( MyXMLSupport )
- initFromXMLRepresentation:(NSXMLElement *)XMLElement;
- (NSXMLElement *)XMLRepresentation;
@end
Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport);
5.遵守协议
@interface ClassName : ItsSuperclass < protocol list >
@interface ClassName ( CategoryName ) < protocol list >
@interface Formatter : NSObject < Formatting, Prettifying >
if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) {
// Object does not conform to MyXMLSupport protocol
// If you are expecting receiver to implement methods declared in the
// MyXMLSupport protocol, this is probably an error
}Chapter 5 Declared Properties
1.属性的重新定义
// public header file
@interface MyObject : NSObject {
NSString *language;
}
@property (readonly, copy) NSString *language;
@end
// private implementation file
@interface MyObject ()
@property (readwrite, copy) NSString *language;
@end
@implementation MyObject
@synthesize language;
@end2.copy
@property (nonatomic, copy) NSString *string;
-(void)setString:(NSString *)newString {
if (string != newString) {
[string release];
string = [newString copy];
}
}可能新的新的string是mutable,而copy返回一个immutable版本@interface MyClass : NSObject {
NSMutableArray *myArray;
}
@property (nonatomic, copy) NSMutableArray *myArray;
@end
@implementation MyClass
@synthesize myArray;
- (void)setMyArray:(NSMutableArray *)newArray {
if (myArray != newArray) {
[myArray release];
myArray = [newArray mutableCopy];
}
}
@end
本文介绍了Objective-C中的对象分配与初始化过程,包括NSObject的alloc方法作用、初始化方法的正确使用方式及返回值,同时探讨了单例模式的具体实现。此外,还讲解了协议的概念及其在正式与非正式情况下的应用,并介绍了属性的声明与实现方法。
132

被折叠的 条评论
为什么被折叠?



