我使用领域数据库,并从数据库在后台队列中加载数据。来自数据库的数据必须在后台加载,之后必须重新加载视图(TableView)。我如何在主线程的tableView上重新加载数据?
这种加载数据的方法:
func loadMenu(category: String) -> [Recipe] {
var ingredient = [Ingredient]()
var stage = [CookStage]()
var photo = [PhotoDish]()
var recipe = [Recipe]()
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
let data = realm.objects(Dish.self).filter("type = '\(category)'")
print(data)
for (index, value) in data.enumerated() {
for valIngredient in value.ingredient {
let ing = ["recipeID": valIngredient.recipeID,
"name": valIngredient.name,
"count": valIngredient.count,
"weight": valIngredient.weight,
"photo": valIngredient.photoURL,
"image": self.loadImage(url: valIngredient.photoURL, dir: "ingredients") ] as [String: AnyObject]
let newIngredient = Ingredient(dict: ing as Dictionary<String,AnyObject>)
ingredient.append(newIngredient)
}
for valCook in value.cook {
let cook = ["stage": valCook.stage,
"recipeID": valCook.recipeID,
"photoUrl": valCook.photoUrl,
"photo": self.loadImage(url: valCook.photoUrl, dir: "stage")] as [String:AnyObject]
let newStage = CookStage(dict: cook as Dictionary<String, AnyObject>)
stage.append(newStage)
}
for valFoto in value.foto {
let foto = ["url": valFoto.url,
"recipeID": valFoto.recipeID,
"image": self.loadImage(url: valFoto.url, dir: "compleate")] as [String:AnyObject]
let newPhoto = PhotoDish(dict: foto as Dictionary<String, AnyObject>)
photo.append(newPhoto)
}
let newElement = Recipe(name: value.name, count: value.eat, complexity: value.complexity, time: value.time, category: value.category, type: value.type, about: value.about, ingredient: ingredient, cook: stage, photo: photo, idOwner: value.idOwner, shared: value.shared, planing: value.planing, recipeID: value.recipeID)
recipe.append(newElement)
}
}
}
return recipe
}
答案 0 :(得分:1)
将数据加载到后台线程后,请使用:
DispatchQueue.main.async {
myTable.reloadData()
}
答案 1 :(得分:0)
//请使用完成处理程序。
#include <utility>
template <char ... Chars>
struct type_string_t {
static constexpr const char data[sizeof... (Chars)] = {Chars...};
};
template <char s(std::size_t), std::size_t... I>
auto type_string_impl(std::index_sequence<I...>) {return type_string_t<s(I)...>();};
#define type_string(s) decltype (type_string_impl<[](std::size_t i) {return s[i];}> \
(std::make_index_sequence<sizeof (s)>()))
static_assert (std::is_same<type_string("String_A"),
type_string("String_A")>::value);
static_assert (!std::is_same<type_string("String_A"),
type_string("String_B")>::value);