iOS asynchronous loading of tabular data and content cannot be displayed in time

Source: Internet
Author: User
Tags closure sqlite database uikit

Asynchronous event, which means that this code or code block does not block the execution of the program, the program immediately executes the next statement, and the statement executes its own callback function after the corresponding method call completes, sending a signal to indicate that the asynchronous event is complete. Just like you're dating 1 hours before you get to the meeting place, go and buy something (...). , wait until GF/BF to inform you, you will come back immediately. Instead of always waiting for each other to come over. )

The earliest use of asynchronous development is when using JavaScript to develop the Web front-end, in XMLHttpRequest or jquery $.ajax, a callback function is used to indicate the success or failure of the processing method. After the corresponding network request has been responded to, calls the response's success or failure callback function, and then executes the corresponding method, which greatly improves the efficiency of the front end, does not stop the entire page when the network requests it, and does not require a poll to see if there is a response, simplifying the complexity of the code.

This is more common in node.js, but it is also more expressive of the misuse of asynchronous event programming. New people use Node.js will always find that basically anything is asynchronous, the database is asynchronous, IO file operation is asynchronous, session read and write is asynchronous, even get the request object are asynchronous. This leads many people to be nesting callback functions, leading to the famous callback Hell

In Node.js, the solution has a very mature async, more known to use synchronous thinking to write asynchronous promises, are a great solution. The essence of the former is a package that automatically generates callbacks ... and the latter is a truly new solution.

And in the development of Swift and iOS, there are also places where asynchronous event programming must be used. In addition to the interaction between the simple UI and the controller of the view layer (which generally does not require handwritten code to process asynchronous interactions or sequences), many other places require this knowledge. such as an asynchronous call to a network request, request queue processing (although a network request is a thread, but this method is inefficient, and easily lead to conflict between threads), SQLite database A large number of data reading and writing, local storage of large amounts of data read and write, complex UI rendering order, etc. These are all asynchronous programming, and cannot allow synchronized code to block the entire application or UI.

For example, here is a UI-loaded animation ...

Func schoollifeclicked ()
{
    var mydrawercontroller = self.mm_drawercontroller// A TableView implementation of the application side bar drawer view
    Let Schoollifeviewcontroller:schoollifeviewcontroller = Schoollifeviewcontroller (nibname: "Schoollifeviewcontroller", Bundle:nil)
    Let Navschoollifeviewcontroller = Commonnavviewcontroller (Rootviewcontroller:schoollifeviewcontroller)

Self.mm_drawerController.toggleDrawerSide (Mmdrawerside.left, Animated:true, completion:{(complete) in
If complete{//if successful pull out drawer
Mydrawercontroller.setcenterviewcontroller (Navschoollifeviewcontroller, Withcloseanimation:true, Completion:nil) Set main view
Mydrawercontroller.closedraweranimated (True, Completion:nil)//close Drawer
}
})//a closure, called after success
}

As you can see, swift can often rely on callback functions to throw a closure into the parameters and then execute to control the flow of this asynchronous event ...

However, this method is written, you'll go back to the anonymous function closure with JS. When the parameters are the same, small scope can also be used, once you want to carry out complex process control, such as a series of asynchronous events, AB simultaneous execution, AB simultaneously complete execution after executing c,c execution d ... The code written under this control is the same as the JavaScript callback hell, which is difficult to maintain.

What do we do? In fact, it is not difficult to implement a grammatical sugar or function queue, but here you can recommend a very powerful library GitHub, how do we use it? Refer to other people's readme, using the grammar of sugar can be very simple to use:

async.userinitiated {
println ("Start")
}.main {
println ("1")
}.background {
println ("2")
}.background {
println ("2 All the Same")
}.main {
println ("Stop")
Because of the characteristics of asynchronous events, the entire output might be

Start
1
2
Stop
2 All the same don't make a fuss. This can be freed from the heavy callback, simple to handle the sequence of asynchronous events, and obtain high performance, which is also a network request and database access must be considered where ...


iOS asynchronously loads tabular data, and the content doesn't show up in time


1, problem description

When we use TableView, the contents of the table are loaded asynchronously. For example, obtain data from the network display, or open a thread queue timed refresh load table data.

(1) For example, we want to load the data as follows:
[
{
"Name": "Hangge",
"Age": 100,
},
{
"Name": "Big Boss",
"Age": 1,
},
{
"Name": "Batman",
"Age": 12,
}
]

(2) After obtaining remote data using Nsurlsession, call the TableView Reloaddata () method to reload the data.

Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var ctrlnames:nsarray = []
var tableview:uitableview?

Override Func Viewdidload () {
Super.viewdidload ()

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)

Creating Nsurl Objects
Let urlstring:string= "http://www.hangge.com/code/test.php"
Let url:nsurl! = Nsurl (string:urlstring)
Create a Request object
Let request:nsurlrequest = Nsurlrequest (Url:url)
Let session = Nsurlsession.sharedsession ()

Let Datatask = session.datataskwithrequest (Request,
Completionhandler: {(data, response, error)-> Void in
If error!= nil{
Print (error?). Code
Print (error?). Description
}else{
Self.ctrlnames = try! Nsjsonserialization.jsonobjectwithdata (data!,
Options:NSJSONReadingOptions.MutableContainers) as! Nsarray
Self.tableview? Reloaddata ()
}
}) as Nsurlsessiontask

To start a task by using the Resume method
Datatask.resume ()
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.ctrlnames.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Cell.accessorytype = Uitableviewcellaccessorytype.disclosureindicator
Let item = Self.ctrlnames[indexpath.row] As! Nsdictionary
Cell.textlabel? Text = Item.objectforkey ("name") as? String
return cell
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

(3) but will find the data loaded after the table is still blank, drag a little table data is displayed.
Original: Swift-load tabular data asynchronously, content not displayed in time to solve the original problem: Swift-load table data asynchronously, the content can not be displayed in time to solve the problem

2, the solution

The Reloaddata () method needs to be invoked in the main thread so that tabular data can be updated in a timely manner. (The code is highlighted as a modified place)

Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var ctrlnames:nsarray = []
var tableview:uitableview?

Override Func Viewdidload () {
Super.viewdidload ()

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)

Creating Nsurl Objects
Let urlstring:string= "http://www.hangge.com/code/test.php"
Let url:nsurl! = Nsurl (string:urlstring)
Create a Request object
Let request:nsurlrequest = Nsurlrequest (Url:url)
Let session = Nsurlsession.sharedsession ()

Let Datatask = session.datataskwithrequest (Request,
Completionhandler: {(data, response, error)-> Void in
If error!= nil{
Print (error?). Code
Print (error?). Description
}else{
Self.ctrlnames = try! Nsjsonserialization.jsonobjectwithdata (data!,
Options:NSJSONReadingOptions.MutableContainers) as! Nsarray

Dispatch_async (Dispatch_get_main_queue (), {
Self.tableview? Reloaddata ()
Return
})
}
}) as Nsurlsessiontask

To start a task by using the Resume method
Datatask.resume ()
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.ctrlnames.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Cell.accessorytype = Uitableviewcellaccessorytype.disclosureindicator
Let item = Self.ctrlnames[indexpath.row] As! Nsdictionary
Cell.textlabel? Text = Item.objectforkey ("name") as? String
return cell
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.