objective-C 基本概念和语法总结

本文介绍了Objective-C中的对象分配与初始化过程,包括NSObject的alloc方法作用、初始化方法的正确使用方式及返回值,同时探讨了单例模式的具体实现。此外,还讲解了协议的概念及其在正式与非正式情况下的应用,并介绍了属性的声明与实现方法。


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;
 
@end


3.非正式协议通常声明为NSObject的categories,但是不需要相应的实现(与category不同)。遵守该协议的对象,在接口文件中再次声明协议方法,并定义其具体实现
@interface NSObject ( MyXMLSupport )
- initFromXMLRepresentation:(NSXMLElement *)XMLElement;
- (NSXMLElement *)XMLRepresentation;
@end

4.正式协议由一个协议类的实例表示,协议对象由运行时系统自动创建
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;
@end

2.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









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值