How can I get OCMock under ARC to stop nilling an NSProxy subclass set using a weak property?

前端 未结 3 1205
夕颜
夕颜 2020-12-31 12:01

Under ARC, I have an object, Child that has a weak property, parent. I\'m trying to write some tests for Child

3条回答
  •  我在风中等你
    2020-12-31 12:29

    Sure. It's going nil because immediately after assigning child.parent, your proxy object itself is released by your test (since it's no longer referenced), and this causes the weak reference to nil out. So the solution is to keep your proxy object alive during the test. You can do this trivially by inserting a call to

    [aParent self];
    

    at the end of your method. That function call does nothing (-self just returns self), but it will ensure that ARC keeps the object alive.

    An alternative would be to change your declaration of aParent to be __autoreleasing, which makes it behave more like MRR in that ARC will just leave an autoreleased reference in that slot instead of explicitly releasing the object when the variable goes out of scope. You can do that with

    __autoreleasing OCMockObject *aParent = ...
    

    That said, the first solution is probably cleaner, because you're explicitly keeping the object alive during the test.

提交回复
热议问题