无法将对象添加到NSMutableArray

时间:2015-09-03 05:11:26

标签: ios swift parse-platform

大家好我正在尝试Swift和Parse,也许你可以在这里给我提示,我不知道为什么我的NSMutableArray typeAccessory总是空的,没有对象,我正在尝试从Parse添加对象。

[编辑]

我试图使用XLForm执行选择器操作表,操作表需要一个元素数组,我想将对象从解析传递给“row.selectorOptions”作为数组。

// XLForm

row = XLFormRowDescriptor(tag :Tags.ActionSheet.rawValue, rowType:XLFormRowDescriptorTypeSelectorActionSheet, title:"Sheet")
        row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
        row.value = "Option 3"
        section.addFormRow(row)

有什么想法吗?

谢谢

   override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: "submit:")
            self.loadAccessoryType() //loading function
    }    

    func loadAccessoryType()-> NSMutableArray{
         var typeAccessory:NSMutableArray? = NSMutableArray()
         var query = PFQuery(className:"accessory_type")
         query.selectKeys(["type"])
         query.findObjectsInBackgroundWithBlock {
             (objects: [AnyObject]?, error: NSError?) -> Void in
                if error == nil {
                   if let objects = objects as? [PFObject] {
                        for object in objects{
                            typeAccessory?.addObject(object["type"]!)
                         }
                      }
                   }else{
                        println("No results")
                   }
               }
            return typeAccessory!
}

2 个答案:

答案 0 :(得分:0)

findObjectsInBackgroundWithBlock将异步工作,因此该方法将跳过''这段代码直接转到return typeAccessory,它总是一个空数组。考虑使用findObjects方法,或者如果您坚持异步尝试使用回调:

func loadAccessoryType(){
     var typeAccessory : NSMutableArray = NSMutableArray()
     var query = PFQuery(className:"accessory_type")
     query.selectKeys(["type"])
     query.findObjectsInBackgroundWithBlock {
         (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil {
               if let objects = objects as? [PFObject] {
                    for object in objects{
                        typeAccessory.addObject(object["type"]!)
                     }
                    self.onAddingObjectsCompleted(typeAccessory)
                  }
               }else{
                    self.onAddingObjectsFailed()
               }
           }

func onAddingObjectsCompleted(data : NSMutableArray) { 
//stuff to do when its done
}

func onAddingObjectsFailed() { 
//stuff to do when it failed
}

答案 1 :(得分:0)

尝试使用

var typeAccessory:NSMutableArray = []

而不是

var typeAccessory:NSMutableArray? = NSMutableArray()

这会产生一个空数组,并且评论上下文不清楚!

添加对象

typeAccessory.addObject(yourObject)
希望它会对你有所帮助!