标签:
This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.
Person *p1=[person alloc];
Person *p2=[p1 init];
+ (3)以上两个过程整合为一句:Person *p=[[Person alloc] init];
说明:
objc The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.
An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.
所以下面两句的作用是等价的 objc Person *p1 = [Person new]; Person *p = [[Person alloc] init];
iOS 程序通常使用[[类名 alloc] init] 的方式创建对象,因为这个可以与其他initWithXX:...的初始化方法,统一来。代码更加统一
格式:[实例对象 class ];
如: [dog class];
格式:[类名 class];
如:[Dog class]
[Dog test];
Class c = [Dog class];
[c test];
Dog *g = [Dog new];
Class c = [Dog class];
Dog *g1 = [c new];
Objective-C是一门面向对象的编程语言。
在Xcode中按Shift + Command + O打开文件搜索框,然后输入NSObject.h和objc.h,可以打开 NSObject的定义头文件,通过头文件我们可以看到,NSObject就是一个包含isa指针的结构体,如下图所示:
NSObject.h
@interface NSObject <NSObject> {
Class isa OBJC_ISA_AVAILABILITY;
}
objc.h
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;
/// Represents an instance of a class.
struct objc_object {
Class isa OBJC_ISA_AVAILABILITY;
};
runtime.h
struct objc_class {
Class isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
Class super_class OBJC2_UNAVAILABLE;
const char *name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE;
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
因为类也是一个对象,那它也必须是另一个类的实例,这个类就是元类 (metaclass)。
类方法
的列表。当一个类方法
被调用时,元类会首先查找它本身是否有该类方法的实现,如果没有则该元类会向它的父类查找该方法,直到一直找到继承链的头。类方法
的定义是保存在元类(metaclass)中,而方法调用的规则是,如果该类没有一个方法的实现,则向它的父类继续查找。所以为了保证父类的类方法可以在子类中可以被调用,所以子类的元类会继承父类的元类,换而言之,类对象和元类对象有着同样的继承关系。下面这张图或许能够 让大家对isa和继承的关系清楚一些
@implementation Person
+ (void)load
{
NSLog(@"%s", __func__);
}
@end
@implementation Student : Person
+ (void)load
{
NSLog(@"%s", __func__);
}
@end
输出结果:
+[Person load]
+[Student load]
@implementation Person
+ (void)initialize
{
NSLog(@"%s", __func__);
}
@end
@implementation Student : Person
+ (void)initialize
{
NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
Student *stu = [Student new];
return 0;
}
输出结果:
+[Person initialize]
+[Student initialize]
标签:
原文地址:http://www.cnblogs.com/zhoudaquan/p/5015797.html