Please explain class error - I have many such conflicts

In my Applescript work to date, I have come across many occasions where I have conflicts of class when errors are reported. Can someone please explain the reason for this, and how you overcome the problem.

For example, I created this simple - I thought - script to get the value of the nickname field of a selected contact in the address book:

tell application "Address Book"
	activate
	set mySelection to selection
	set nName to nickname of mySelection
	return nName
end tell

It replied with the following error message. Please explain…

tell application “Address Book”
activate
get selection
→ {person id “2A32CCD5-2873-4B10-94A1-E17DF9F38A37:ABPerson”}
Result:
error “Can’t get nickname of {person id "2A32CCD5-2873-4B10-94A1-E17DF9F38A37:ABPerson" of application "Address Book"}.” number -1728 from «class az43» of {«class azf4» id “2A32CCD5-2873-4B10-94A1-E17DF9F38A37:ABPerson”}

Hi,

in most applications selection returns a list.
You can see that in the error message, the braces represent a list.
Can’t get nickname of {person i. "Address Book"}


tell application "Address Book"
	activate
	set mySelection to selection
	set nName to nickname of (item 1 of mySelection)
	return nName
end tell

According to the parentheses in your event log, the object returned by selection is a list. You’ll either have to loop it, or you’ll have to pick out one item to process.


-- Using a loop
tell application "Address Book"
	set mySelection to selection
	my NicknamesOfObjectsInList(mySelection)
end tell

on NicknamesOfObjectsInList(l)
	tell application "Address Book"
		set lc to count l
		set newl to {}
		repeat with i in l
			set end of newl to nickname of i
		end repeat
	end tell
	return newl
end NicknamesOfObjectsInList

-- Process only the first item
tell application "Address Book"
	set mySelection to selection
	get nickname of item 1 of mySelection
end tell

Ok, Stefan - that makes perfect sense. I tried with a number of selections, and the system still worked. What does not seem to be clear, and something that I also experienced when I produced another list from the address book previously in another script is the order of the selections so that you can get the right selection as item 1.

How do you sort the list to get the choices to be arranged alphabetically?