1

I'm getting the "Error #1009: Cannot access a property or method of a null object reference." error on my application. Is there a function I can use to detect this before it causes an error... maybe something like:

isValid(variableName);

I know there's one, because i've used it before, but i can't remember what it is right now.

Any help would be greatly appreciated.

Brds
  • 1,035
  • 3
  • 17
  • 37
  • 1
    http://stackoverflow.com/questions/296861/test-if-an-object-is-defined-in-actionscript Same question right there – az4dan Jul 15 '11 at 20:38
  • 1
    I voted to close due to the duplicate question. http://stackoverflow.com/questions/296861/test-if-an-object-is-defined-in-actionscript – JeffryHouser Jul 15 '11 at 20:45
  • Nope... this isn't the same. There's different way. Ugh, I'll keep on looking for it. I'll post it when i find it. – Brds Jul 15 '11 at 21:10

4 Answers4

2

My guess: hasOwnProperty

okulin
  • 121
  • 4
2

Simply put, a null object maps to a Boolean false. suppose:

var x:ArrayCollection; //uninitialised
if(x) {
    Alert.show("X");
} else {
    Alert.show("NOT X");
}

Above code will show an alert saying NOT X because a null variable maps to false

However, if you want to check whether an object has a property with a particular name, try

var o:MyObject=new MyObject();
if(o.hasOwnProperty("something")) {
    Alert.show(o.something);
} else {
    Alert.show("Something undefined");
}

now if there is a property called "something" on o, EVEN IF ITS VALUE IS null, it will go into if()... otherwise it will go into else.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
1

A simple if statement will work.

if (myVariable)
{
  //do something
}

UPDATE: After looking at the code that's causing the error, my guess is that either wholeProject[j] is null or wholeProject[j].wholePosition is null. Try something like this:

if (wholeProject[j] && wholeProject[j].wholePosition)
{
  for (var k:int = 0; k < wholeProject[j].wholePosition.length; k++)
}
Jason Towne
  • 8,014
  • 5
  • 54
  • 69
1

It's actually quite simple. Use a try/catch construct with the (err:) For example, I use this to surround parsing code that can generate errors. "Error" means any error.

try { relation.parseObject(XMLObject["relation"],source); } 
catch (err:Error) {tr.output(mN + "bad relation " + err)}; 

You would do this:

try {
newvalue = variableName;
}
catch (error:ReferenceError) { <do something> }
deeeptext
  • 41
  • 6