In-depth introduction to the dynamic creation class of Cocoa

Source: Internet
Author: User
In the previous article "go deep into Cocoa and other objects", I have introduced in detail
The concept of Class and Object. How can we run it today?

Hour

Dynamically create a class. The following function applies the Class and MetaClass concepts mentioned above to dynamically create a Class at runtime. This function comes from Inside
Mac OS X-The Objective-C Programming Language.

# Import <objc/objc. h>
# Import <objc/runtime. h>

BOOL CreateClassDefinition (const char * name, const char * superclassName)
{
Struct objc_class * meta_class;
Struct objc_class * super_class;
Struct objc_class * new_class;
Struct objc_class * root_class;
Va_list args;

// Ensure that the parent class exists
Super_class = (struct objc_class *) objc_lookUpClass (superclassName );
If (super_class = nil)
{
Return NO;
}

// Make sure the class to be created does not exist
If (objc_lookUpClass (name )! = Nil)
{
Return NO;
}

// Find the root class because the isa of the meta class points to the meta class of the root class.
Root_class = super_class;
While (root_class-> super_class! = Nil)
{
Root_class = root_class-> super_class;
}

// Allocate memory for the class and its meta class
New_class = calloc (2, sizeof (struct objc_class ));
Meta_class = & new_class [1];

// Set the class
New_class-> isa = meta_class;
New_class-> info = CLS_CLASS;
Meta_class-> info = CLS_META;

// Copy the class name. To improve the efficiency, both the class and meta class point to the same class name string.
New_class-> name = malloc (strlen (name) + 1 );
Strcpy (char *) new_class-> name, name );
Meta_class-> name = new_class-> name;

// Assign and leave the empty method lists, which can be used later

Class_addMethods Add a method to the class

 
New_class-> methodLists = calloc (1, sizeof (struct objc_method_list *));
Meta_class-> methodLists = calloc (1, sizeof (struct objc_method_list *));

// Add the class to the inheritance system:
// 1. Set the super class of the class.
// 2. Set the super class of the meta class.
// 3. Set isa for meta class
New_class-> super_class = super_class;
Meta_class-> super_class = super_class-> isa;
Meta_class-> isa = (void *) root_class-> isa;

// Finally, register the class to the runtime system
Objc_addClass (new_class );

Return YES;
}


To use runtime-related functions in the code, we need to import libobjc. dylib and related header files (such as runtime. h ).

In the previous article, we summarized "ObjC
Generate two objc_class for each class definition. One is a common class and the other is metaclass. We can create the two objc_class data structures at runtime, and then use objc_addClass to dynamically create a new class definition .", This is reflected in the above Code: new_class
And meta_class are the two objc_classes required by the new class. Other codes are not explained. Comments and codes are self-explanatory.

In actual use, we use the ObjC runtime function to dynamically create classes:
Class objc_allocateClassPair (Class superclass, const char * name, size_t extraBytes );


For example:
# Import <objc/objc. h>
# Import <objc/runtime. h>

Void ReportFunction (id self, SEL _ cmd)
{
NSLog (@ "> This object is % p.", self );
NSLog (@ "> Class is % @, and super is % @.", [self class], [self superclass]);

Class prevClass = NULL;
Int count = 1;
For (Class currentClass = [self class]; currentClass; ++ count)
{
PrevClass = currentClass;

NSLog (@ "> Following the isa pointer % d times gives % p", count, currentClass );

CurrentClass = object_getClass (currentClass );
If (prevClass = currentClass)
Break;
}

NSLog (@ "> NSObject's class is % p", [NSObject class]);
NSLog (@ "> NSObject's meta class is % p", object_getClass ([NSObject class]);
}

Int main (int argc, const char * argv [])
{

@ Autoreleasepool
{
Class newClass = objc_allocateClassPair ([NSString class], "NSStringSubclass", 0 );
Class_addMethod (newClass, @ selector (report), (IMP) ReportFunction, "v @:");
Objc_registerClassPair (newClass );

Id instanceOfNewClass = [[newClass alloc] init];
[InstanceOfNewClass extends mselector: @ selector (report)];
[InstanceOfNewClass release];
}

Return 0;
}


In the above Code, we create a subclass NSStringSubclass that inherits from NSString, and then add a method to it.
Report, and register it in the runtime system, so that we can use this new class. Here, the performSelector is used to send messages to the new class object, which can avoid compilation of warning messages (because we have not declared the class and its responsive messages ).

The execution result is:
> This object is 0x100114710.
> Class is NSStringSubclass, and super is NSString.
> Following the isa pointer 1 times gives 0x100114410
> Following the isa pointer 2 times gives 0x100114560
> Following the isa pointer 3 times gives 0x7fff7e257b50
> NSObject's class is 0x7fff7e257b78
> NSObject's meta class is 0x7fff7e257b50


Based on the class relationship diagram above, it is not difficult to analyze the internal class structure of NSStringSubclass from the execution results:
1. The object address is 0x100114710.
2. class address: 0x100114410
3. The meta class address is 0x100114560.
4. The class address of the meta class is 0x7fff7e257b50 (also
NSObject meta class)
5. The meta class of NSObject's meta class is its own

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.