A
A
artursk2016-09-04 16:45:31
Objective-C
artursk, 2016-09-04 16:45:31

How to call an element of a complex array?

In plist (for further use with cordata) I store a list of exercises from three items, which in turn contain the names of these three complexes and a list of several exercises in each complex. File description of sets of exercises

import Foundation

class Exersise: NSObject {

var name: String!
var image: String!
var exersiseDescript: String!

init(name: String, image: String, exersiseDescript: String){
    super.init()
    self.name = name
    self.image = image
    self.exersiseDescript = exersiseDescript
}

static var sectionNames: [String] = [] // НАЗВАНИЕ КОМПЛЕКСА УПРАЖНЕНИЙ, ОТОБРАЖАЕТСЯ В НАЗВАНИИ СЕКЦИЙ ТАБЛИЦЫ

static var all:  = {

    var allObjects:  = []
    let path = NSBundle.mainBundle().pathForResource("Exersises", ofType: "plist")
    let objects = try! NSPropertyListSerialization.propertyListWithData(NSData(contentsOfFile: path!)!, options: .MutableContainersAndLeaves, format: nil) as! NSArray

    for object in objects {
        sectionNames.append(object["name"] as! String)
        var subArray: [Exersise] = []
        for item in object["items"] as! NSArray {
            subArray.append(Exersise(name: item["name"] as! String, image: item["image"] as! String, exersiseDescript: item["exersiseDescript"] as! String))
        }
        allObjects.append(subArray)
    }
    return allObjects
}()
}

The main controller for access to exercise complexes
import UIKit
import StoreKit

var buyArray = [0]

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    if (NSUserDefaults.standardUserDefaults().objectForKey("Buy") != nil){
        buyArray = NSUserDefaults.standardUserDefaults().objectForKey("Buy") as! Array
        print("buyArray = \(buyArray)")
    }
}

@IBAction func firstButton(sender: UIButton) {
    print("Первый комплекс бесплатен")
}

@IBAction func SecondButton(sender: UIButton) {
    print("Куплен второй комплекс")
    buyArray.append(1) // ДОБАВЛЯЕМ КУПЛЕННЫЕ УПРАЖНЕНИЯ В МАССИВ buyArray
    print("buyArray = \(buyArray)")
    NSUserDefaults.standardUserDefaults().setObject(buyArray, forKey: "Buy")
}

@IBAction func ThirdButton(sender: UIButton) {
    print("Куплен третий комплекс")
    buyArray.append(2) // ДОБАВЛЯЕМ КУПЛЕННЫЕ УПРАЖНЕНИЯ В МАССИВ buyArray
    print("buyArray = \(buyArray)")
    NSUserDefaults.standardUserDefaults().setObject(buyArray, forKey: "Buy")
}}

In the third controller, we display the acquired exercises, it is here that when calling the name of the section, it gives an error...
import UIKit
import CoreData

class AllExersiseTableViewController: UITableViewController {

private var exersises:  = []
private var selected: Set<NSIndexPath> = []
private var sectionCount = 1

override func viewDidLoad() {
    super.viewDidLoad()

    var allBuy = ["ONE", "TWO", "THREE"]
    var buyForTableView = [String]()
    if (NSUserDefaults.standardUserDefaults().objectForKey("Buy") != nil){
        buyArray = NSUserDefaults.standardUserDefaults().objectForKey("Buy") as! Array
    }

    for element in buyArray {
        buyForTableView.append(allBuy[element])
    }
    print(buyForTableView)

    if buyForTableView == ["ONE"]{
        let index = Exersise.sectionNames.indexOf("ONE")! // Название секции в plist
        exersises.append(Exersise.all[index])
    } else if buyForTableView == ["ONE", "TWO"]{
        var index = Exersise.sectionNames.indexOf("ONE")!
        exersises.append(Exersise.all[index])
        index = Exersise.sectionNames.indexOf("TWO")!
        exersises.append(Exersise.all[index])
    } else if buyForTableView == ["ONE", "THREE"]{
        var index = Exersise.sectionNames.indexOf("ONE")!
        exersises.append(Exersise.all[index])
        index = Exersise.sectionNames.indexOf("THREE")!
        exersises.append(Exersise.all[index])
    } else if buyForTableView == ["ONE", "TWO", "THREE"] || buyForTableView == ["ONE", "THREE", "TWO"]{
        var index = Exersise.sectionNames.indexOf("ONE")!
        exersises.append(Exersise.all[index])
        index = Exersise.sectionNames.indexOf("TWO")!
        exersises.append(Exersise.all[index])
        index = Exersise.sectionNames.indexOf("THREE")!
        exersises.append(Exersise.all[index])
    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return exersises.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return exersises[section].count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    let object = exersises[indexPath.section][indexPath.row]

    cell.textLabel?.text = object.name
    cell.imageView?.image = UIImage(named: object.image)
    cell.accessoryType = selected.indexOf(indexPath) != nil ? .Checkmark : .None
    return cell
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return Exersise.sectionNames[section]
}

private func addWorkout(name: String) {
    let manager = CoreDataManager.defaultManager()
    let workout = NSEntityDescription.insertNewObjectForEntityForName("Workout", inManagedObjectContext: manager.managedObjectContext) as! Workout
    workout.creationDate = NSDate()
    workout.name = name
    workout.items = NSKeyedArchiver.archivedDataWithRootObject(selected)
    manager.save()
}
}

Here is an example of an error For those who are
1c8a427166824f428e4b7eb65b9601c1.png
interested, a link to the project https://yadi.sk/d/Eh4yTEgiukyYT Thank you all for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TramPamPamm, 2016-09-08
@TramPamPamm

Looks like you don't have "ONE" in the Exersise.sectionNames array Print
it to the log
And yes, use if let to form the index - it will crash less ;)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question