Objective_CExtensionMechanismLearning is the content to be introduced in this article.Objective_CIt has been one year since the iphone was developed. FirstObjective_CWhen c/c ++ is used, the knowledge learned is based on c/c ++. In factObjective_CThe superset of C was not realized at that time, and its essence was not understood at all. Learn more with the passage of time.
Objective_CIt is more powerful than c/c ++ because it contains some design patterns. I have heard that java includes almost all the design patterns, but I have never used java in depth, and I have used j2s to write a little logic. The two most flexible aspects of Objective_C are: category and associative. I classify them as extensions of Objective_C.Mechanism. Category can extend a class method, and associative can extend the attributes of a class. The functions of these two methods are equivalent to the inheritance in c ++.
Let's take a look at the associative column. The header file is required:
- #import <objc/runtime.h>
-
- static char overviewKey = 'a';
- NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];
- // For the purposes of illustration, use initWithFormat: to ensure
- // we get a deallocatable string
- NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];
- objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
- [overview release];
- NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
- NSLog(@"associatedObject: %@", associatedObject);
- objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );
- [array release];
- static char overviewKey = 'a';
- NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];
- // For the purposes of illustration, use initWithFormat: to ensure
- // we get a deallocatable string
- NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];
- objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
- [overview release];
- NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
- NSLog(@"associatedObject: %@", associatedObject);
- objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );
- [array release];
Objc_setAssociatedObject adds an attribute to the array. We can obtain this attribute through the key. See the code above: objc_getAssociatedObject. If the second objc_setAssociatedObject is set to nil, this attribute is deleted.
Here is another example: callback.
Summary: DetailsObjective_CExtensionMechanismI hope this article will be helpful to you!