If you mega-evolve and then switch Pokemon during the same battle, the Pokemon will remain Mega for the duration of the battle, even when no longer in the battle itself. It'll only revert after the battle is finished. As for fainting, I'm not too sure, but I think the Pokemon will remain Mega when fainted, then revert at the end of the battle.