Association refers to associating two objects together so that one of the objects is part of another object.
With correlation, we can add storage space to objects without modifying the definition of the class.
Associations are based on keywords, so we can add any number of associations to any object, each with a different keyword.
Create an association
Objc_setassociatedobject
- static char Key;
- Nsarray * Array =[[nsarray alloc] initwidthobjects:@"Red" @"green" @"blue", nil];
- NSString * string = [[NSString alloc] Initwithformat:@"color"];
- Objc_setassociatedobject (Array, &key, String, objc_association_retain);
- [String release];
- (1) string is still available
- [Array release];
- (2) string not available
Get Association Object
Objc_getassociatedobject.
- NSString * Associatedobject = (NSString *) objc_getassociatedobject (array, &key);
Disconnect Association
objc_setassociatedobject function , you can pass in the nil value.
- Objc_setassociatedobject (array, &key, nil, objc_association_assign);
Where the associated object is nil, then the association policy does not matter.
Use the function objc_removeassociatedobjects to disconnect all associations.