Remove item from array using Cocoa

Hi,

I would like to know if is possible to use AppleScript Editor to experiment syntax to populate an array don’t using AS but with Cocoa (before add the code to Xcode ASOC Project).

Basically I need to create a NSMutable array, populate it adding one item at time and after comparison a item is contained in the array remove this item from array:

In AppleScript:

set arrayObjects to {}
copy “A” to end of arrayObjects
copy “B” to end of arrayObjects
copy “C” to end of arrayObjects

if “B” is in arrayObjects then
– delete the item that in AS is not possible
end if

Hagi

You’re probably looking for list methods like indexForObject and removeItemAtIndex. Unfortunately AppleScript doesn’t have these methods. If you know the index and every item in the list is text you could use code like this:

set arrayObjects to {}
copy "A" to end of arrayObjects
copy "B" to end of arrayObjects
copy "C" to end of arrayObjects

if "B" is in arrayObjects then
	set item 2 of arrayObjects to missing value
	set arrayObjects to text of arrayObjects
end if

Hi,

this is the AppleScript “replica” of the NSMutableArray methods indexOfObject: and removeObjectAtIndex:


set array to {"alpha", "beta", "gamma", "delta", "epsilon"}
set theIndex to indexOfObject("delta", array)
if theIndex is not 0 then
	set theList to removeObject from array at theIndex
end if

-- removeObjectAtIndex
on removeObject from aList at anIndex
	if anIndex is 1 then
		return rest of aList
	else if anIndex is (count aList) then
		return items 1 thru -2 of aList
	else
		return (items 1 thru (anIndex - 1) of aList) & (items (anIndex + 1) thru -1 of aList)
	end if
end removeObject

-- indexOfObject
on indexOfObject(anItem, aList)
	repeat with i from 1 to (count aList)
		if item i of aList is anItem then return i
	end repeat
	return 0
end indexOfObject

Note: Be aware that indexes in AppleScript are 1-based but in Cocoa 0-based

FWIW, that’s precisely one of things my AppleScriptObjC Explorer is designed for.

Thanks for all the replies :wink: