在Swift中,如何停止所有过程,直到从UICOLLECTIONVIEW中的parse.com检索到数据为止 [英] In Swift, how to stop all the process until datas retrieved from parse.com in UICOLLECTIONVIEW

查看:68
本文介绍了在Swift中,如何停止所有过程,直到从UICOLLECTIONVIEW中的parse.com检索到数据为止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CollectionView中,我正在显示来自parse.com的数据.成功检索.但是无法显示在单元格中.我由于阵列出站而收到错误.我发现了错误,解析是作为异步运行的.但是,在解析结束之前,将加载集合视图.因此,我无法在单元格中显示值.它抛出一个错误.如何停止所有过程,直到解析完全加载?请指导我. 我的编码如下:

In CollectionView I am displaying datas from parse.com. Successfully retrieved. But unable to display in the cell. I am receiving error as Array outbound. I found out the mistake, parse is running as asynchronous. But, before parse end, collection view gets loaded. So I unable to display values in the cell. It is throwing an error. How to stop all the process until parse get loaded completely? Kindly guide me. MY CODING IS BELOW:

//VIEWCONTROLLER having collectionView

var myList : NSArray = NSArray()

let obj_par = parse_retrive()
obj_par.parse_DB() //DATAS GOING TO RETRIVE FROM PARSE

story_collection_view.reloadData() //RELOADING COLLECTIONVIEW

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        println("fifth")

        if(collectionView == date_collection_view)
        {
         :
         :
            return cell
        }

        else

        {
            var cell = collectionView.dequeueReusableCellWithReuseIdentifier("story_read", forIndexPath: indexPath) as story_reading_cell

  cell.story_title.text = myList.objectAtIndex(indexPath.row) as? String //ERROR: ARRAY OUTBOUND OF INDEX

            return cell
        }

    }

//PARSE_RETRIVE类别

//PARSE_RETRIVE CLASS

func parse_DB() {

        println("SECOND 10")

        par_query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in

            if (error != nil) {
                NSLog("error " + error.localizedDescription)
            }
            else {
                println("SECOND 13")
                let sql_store_obj1 = sql_to_store() //THIRD CLASS
                self.parse_obj_arr = NSArray(array: objects)
                var j : Int = self.parse_obj_arr.count
                for (var i : Int = 0; i < j; i++) {
                    self.par_object = self.parse_obj_arr.objectAtIndex(i) as PFObject
                    self.sto = self.par_object["story_title"] as String        //STORY TITLE FROM PARSE
                    self.sto_con = self.par_object["story_content"] as String  //STORY CONTENT FROM PARSE

                    self.sto_tit.append(self.sto)        //STORING IN ARRAY VAR
                    self.sto_cont.append(self.sto_con)   //STORING IN ARRAY VAR

                } //FOR ENDING

                sql_store_obj1.sto_title_arr = self.sto_tit
                sql_store_obj1.sto_content_arr = self.sto_cont
                sql_store_obj1.parse_to_sql()

            }//ELSE ENDING

        }) //PARSE QUERY ENDING

        println("SECOND")

    } 

//第三类

func parse_to_sql() {

        let appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context : NSManagedObjectContext = appDel.managedObjectContext!
        let ent = NSEntityDescription.entityForName("Sad", inManagedObjectContext: context)
        var newStory = story_sad_managed(entity: ent!, insertIntoManagedObjectContext: context)

        newStory.story_title = sto_title_arr
        newStory.story_content = sto_content_arr

        let request = NSFetchRequest(entityName: "STORY")
        request.predicate = NSPredicate(format: "story_title = %@", sto_title_arr)
        result  = context.executeFetchRequest(request, error: nil)!

        let sto_page_obj = story_page()
        sto_page_obj.myList = result //1st CLASS ARRAY 

    }

推荐答案

注意: 所有代码都在Objective-C中进行,但是此特定代码的翻译应该很简单.如果有人要编辑我的帖子以包含Swift代码,请放心,但请在帖子中保留Objective-C.

NOTE: All code is in Objective-C, but the translation for this particular code should be trivial. If someone wants to edit my post to include the Swift code, please feel free, but please leave the Objective-C in the post.

我所做的(对于UICollectionViewUITableView)是创建一个通常称为isLoading的属性,如下所示:

What I do (for UICollectionView or UITableView) is create a property, normally called isLoading like this:

@property (assign, nonatomic) BOOL isLoading;

我通常是这样初始化它的:

I normally initialize it like this:

- (void)viewDidLoad {
    [super viewDidLoad];
    // This could also be done in viewWillAppear/viewDidAppear
    // based on your needs/desires
    self.isLoading = NO;
    [self loadData];
}

- (void)loadData {
    if (self.isLoading == YES) {
        // Just in case a "loadData" call is made while one is pending...
        return;
    }
    // Prevent this method from firing again until 
    // data loading is done; prevent UICollectionView
    // from attempting to display missing data
    self.isLoading = YES;

    // Do whatever you need to do...

    // Clean up and prepare for UICollectionView
    self.isLoading = NO;
    [self.collectionView reloadData];
}

现在,真正的秘密当然是,您必须在UICollectionViewDataSource方法中实现逻辑,才能基于self.isLoading有条件地显示数据,如下所示:

Now, the real secret is, of course, that you have to implement logic in your UICollectionViewDataSource methods to display data conditionally based upon self.isLoading, like this:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.isLoading == YES) {
        // You might want to return 0 or 1, 
        // depending on whether you have a "loading"
        // placeholder cell. Assume you do:
        return 1;        
    } else {
        // Return whatever is the correct number here

    }
}

通常,这就是我需要的屏幕,以延迟加载UICollectionView直到解析查询正确返回之前.

Generally, that's all I need to get my screen to delay loading the UICollectionView until the Parse query has returned correctly.

当我有多个将同时运行的查询时,所有这些查询都应在我认为数据加载完成之前返回,然后为每个查询创建一个BOOL属性,并根据需要设置标志,然后对所有程序进行漏斗查询通过checkIfDone方法返回.像这样:

When I have multiple queries that will run concurrently, all of which should return before I consider data loading to be complete, then I create a BOOL property for each of them, setting the flags as appropriate, and I funnel all query returns through a checkIfDone method. Something like this:

@property (assign, nonatomic) BOOL data1Loaded;
@property (assign, nonatomic) BOOL data2Loaded;
@property (assign, nonatomic) BOOL data3Loaded;
@property (assign, nonatomic) BOOL data4Loaded;

- (void)loadData {
    if (self.isLoading == YES) {
        return;
    }
    self.isLoading   = YES;
    self.data1Loaded = NO;
    self.data2Loaded = NO;
    self.data3Loaded = NO;
    self.data4Loaded = NO;

    // Call each of the separate data loading methods...
    [self loadData1];
    [self loadData2];
    [self loadData3];
    [self loadData4];

    // Notice that I don't do any reloadData calls here...

}

- (void)loadData1 {
    PFQuery *query = // Some query creation...
    [query findObjectsInBackgroundWithBlock:
        ^(NSArray *objects, NSError *error) {
            if (error != nil) { 
                // Handle "got error"

            } else {
                // Handle "got good data"

            }
            // Either way, #1 is done, so:
            self.data1Loaded = YES;
            // This pattern checks for completion and
            // runs the completion code only when all
            // 4 (in this case) items/queries have returned
            [self checkIfDone];
        }
     ];
}

- (void)checkIfDone {
    if (self.data1Loaded == YES && 
        self.data2Loaded == YES && 
        self.data3Loaded == YES && 
        self.data4Loaded == YES) 
    {
        // Clean up and prepare for UICollectionView
        self.isLoading = NO;
        [self.collectionView reloadData];
    }
}

提示: :这假定对loadData的任何后续调用都将在后台发生,并且对[collectionView reloadData]的任何后续调用都将仅在末尾进行您的查询调用.如果同时有其他事情可能调用reloadData,则您将需要更高级的逻辑以确保正确加载了正确的数据.

Caveat: This assumes that any subsequent calls to loadData will occur in the background and that any subsequent calls to [collectionView reloadData] will only take place at the end of your query calls. If anything else might call reloadData in the meantime, you will need more advanced logic to ensure that the correct data is loaded correctly.


侧面说明: 在执行此类操作时,请不要忘记向用户显示工作正在进行的指示.我喜欢使用开源MBProgressHUD.可以在GitHub上此处使用.我发现它对于执行您正在谈论的事情非常有价值.

Side Note: When doing something like this, don't forget to show the user an indication that work is progressing. I like to use the open source MBProgressHUD. It's available here on GitHub. I have found it invaluable for doing exactly what you're talking about doing.

这篇关于在Swift中,如何停止所有过程,直到从UICOLLECTIONVIEW中的parse.com检索到数据为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆