How to add pointer to an NSObject custom subclass to an NSMutableArray?

余生颓废 提交于 2019-12-07 02:11:27

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!