It doesn't matter if the moldings are painted first or the walls.
Painting your molding before the walls can be easier since you won't have to cut them into the wall or ceiling with a brush. But you still need a straight line and the moldings will need to be protected with blue painter's masking tape. The tape can provide a straight line but could allow some paint to "bleed" onto the moldings.
Allow 4-6 hours of drying time for the freshly painted molding, more the better, and then apply the tape. When painting the ceiling or walls, carefully cut in to the trim using the tape as a guide. Dry brushing, using the least amount of paint possible, will help to keep the "bleeding" to a minimum.
This is a "six or half dozen of the other" situation. Generally, I paint the large areas first carefully brushing to the moldings for a straight line. Then I paint the moldings by hand with a brush. This way I can finish a room as soon as possible without worrying about taping over fresh paint. Painting this way requires a steady hand and some patience.