What's the best way to communicate between view controllers?

后端 未结 4 1052
野趣味
野趣味 2020-11-22 15:34

Being new to objective-c, cocoa, and iPhone dev in general, I have a strong desire to get the most out of the language and the frameworks.

One of the resources I\'m

4条回答
  •  渐次进展
    2020-11-22 16:30

    Suppose there are two classes A and B.

    instance of class A is

    A aInstance;

    class A makes and instance of class B, as

    B bInstance;

    And in your logic of class B, somewhere you are required to communicate or trigger a method of class A.

    1) Wrong way

    You could pass the aInstance to bInstance. now place the call of the desired method [aInstance methodname] from the desired location in bInstance.

    This would have served your purpose, but while release would have led to a memory being locked and not freed.

    How?

    When you passed the aInstance to bInstance, we increased the retaincount of aInstance by 1. When deallocating bInstance, we will have memory blocked because aInstance can never be brought to 0 retaincount by bInstance reason being that bInstance itself is an object of aInstance.

    Further, because of aInstance being stuck, the memory of bInstance will also be stuck(leaked). So even after deallocating aInstance itself when its time comes later on, its memory too will be blocked because bInstance cant be freed and bInstance is a class variable of aInstance.

    2)Right way

    By defining aInstance as the delegate of bInstance, there will be no retaincount change or memory entanglement of aInstance.

    bInstance will be able to freely invoke the delegate methods lying in the aInstance. On bInstance's deallocation, all the variables will be its own created and will be released On aInstance's deallocation, as there is no entanglement of aInstance in bInstance, it will be released cleanly.

提交回复
热议问题