Desert plants live in a very hostile environment. Any physical damage, such as grazing, can seriously jeopardize their chances of survival. Thus, they have developed "spikes' as a defense mechanism.
Also Cacti have spikes to avoid transpiration (loss of water through stomatal pores on the leaves in the form of vapours) so that they don't lose water as water is scarcely available in the areas they grow in.
Also to protects themselves against predators.