问题
For the following code snippet from ViewController.m:
- (IBAction)buttonAction:(id)sender
{
CustomButton *button = (CustomButton *)sender;
button.associatedObject = [self.sourceOfObjects.objectArray lastObject];
[self.foo.arrayOfObjects addObject:button.associatedObject]; // this does not work?
}
• CustomButton is subclass of UIButton and has @property (nonatomic, strong) associatedObject that is a pointer to an object of type NSObject.
• sourceOfObjects is a @property (nonatomic, strong) of self of type MyCustomObject, a subclass of NSObject.
• objectArray is a @property (nonatomic, strong) of sourceOfObjects of type NSMutableArray.
• foo is a @property (nonatomic, strong) of the ViewController of type MyCustomObject, a subclass of NSObject.
• arrayOfObjects is a @property (nonatomic, strong) of foo of type NSMutableArray.
QUESTION: Any idea why I cannot add the pointer from button.associatedObject to self.foo.arrayOfObjects so that I have a pointer in self.foo.arrayOfObjects that points to the same object as button.associatedObject?
WHAT I EXPECT TO HAPPEN: If I subsequently ask for [self.foo.arrayOfObjects lastObject], it should return the object that button.associatedObject also points to.
WHAT ACTUALLY HAPPENS: Subsequently asking for self.foo.arrayOfObjects.count returns 0. I do not believe it is an issue with initialization of arrayOfObjects as I have lazy instantiation in place.
I hope I phrased this question accurately, tried to be precise. :)
回答1:
I forgot to add lazy instantiation for self.foo.arrayOfObjects within the definition for class MyCustomObject. :S What that means is that within file MyCustomObject.m the following lines were missing:
- (void)setArrayOfObjects:(NSMutableArray *)arrayOfObjects
{
_arrayOfObjects = arrayOfObjects;
}
- (NSMutableArray *)arrayOfObjects
{
if (!_arrayOfObjects) _arrayOfObjects = [[NSMutableArray alloc] init];
return _arrayOfObjects;
}
Because arrayOfObjects was not lazily instantiated within the MyCustomObject class, adding an object to self.foo.arrayOfObjects from within ViewController.m did nothing because self.foo.arrayOfObjects was still null, and adding an object to null procures a null object.
回答2:
I might be wrong here, but NSObject and all it's subclasses are actually pointers. So if you explicitly create a pointer to an NSObject, and then pass that pointer to addObject
, you are passing the pointer to the pointer, and not the pointer to the Object that the method is expecting.
How do you define associatedObject
?
来源:https://stackoverflow.com/questions/10466863/how-to-add-pointer-to-an-nsobject-custom-subclass-to-an-nsmutablearray