refactored coredata writing code