开发者

flex/actionscript assignment failing?

I'm seeing something weird in my actionscript code

I have two classes foo and bar, bar extends foo. In a model class I have a foo member variable, I assign an bar object to the foo variable. But after the assignment the foo variable is null.

[Bindable] public var f:foo;
public function someFunc(arr:ArrayCollection):void  {  
  if(arr.length > 0) {
    var tempBar:bar = arr.getItemAt(0) as bar;
    if(tempBar != null) {
      tempBar.someProp++;
      f = tempBar;
      // f is now null
    }
  }
}

Any ideas on what I could be doing wrong?

EDIT Here is the exact code:

  [Bindable] public var selectedCustomerJob:IDSCustomer;

  public function selectedJobByIdCallback(evt:Event):void
  {
   var temp:IDSDTOArrayCollection = evt.currentTarget as IDSDTOArrayCollection;
   if(null != temp &开发者_Go百科;& temp.length > 0)
   {
    selectedCustomerJob = IDSJob(temp.getItemAt(0));;
    trace("    selectedCustomerJob: " + flash.utils.getQualifiedClassName(selectedCustomerJob));
    trace("       jobToSelect type: " + flash.utils.getQualifiedClassName(temp.getItemAt(0)));
    trace("jobToSelect super class: " + flash.utils.getQualifiedSuperclassName(temp.getItemAt(0)));
   }
  }

this is the trace output:

selectedCustomerJob: null

jobToSelect type: com.intuit.sb.cdm.v2::IDSJob

jobToSelect super class: com.intuit.sb.cdm.v2::IDSCustomer


Casting using the as keyword returns null when it fails. In this case, the first item in the array collection may not be an object of type Bar as you expect; it could be a Foo or something else. You can cast subclass object to base-class but not the other way.

Use the parenthesis syntax for casting - it'll throw an exception if cast fails and thus you can figure out the type of arr.getItemAt(0).

//Change 
var tempBar:Bar = arr.getItemAt(0) as Bar;

//to 
var tempBar:Bar = Bar(arr.getItemAt(0));

to make sure that the first item in the array collection is indeed a Bar instance (and not Foo or something else).

Otherwise you can find the type using

trace(flash.utils.getQualifiedClassName(arr.getItemAt(0)));

if(tempBar != null) {
  tempBar.someProp++;
  f = tempBar;
  // f is now null
}

By the way, I believe the posted code is not the exact code you ran because for f to be null, tempBar should be null as you assigning it to f. In that case the code inside if should not be executed as you're checking for null inside if. Even if it enters the if block, it will throw a null pointer error (#1009) in the first line where you're trying to increment tempBar.someProp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜