如何从获取请求数组结果中分配键和从空字典中输入的文本字段中的值?

时间:2017-03-24 15:48:20

标签: swift dictionary core-data swift3

我有一个获取请求,它返回一个Floors实体的对象数组。对于每个楼层实体,我为“每层房间数”属性分配一个值。下一个vc是一个表格,其中楼层数量需要是部分,每层楼的房间数量需要是该部分内的单元格。因此,我能想到的最方便的方法是传递字典[floor:roomsInFloor]以准备segue。问题是我无法理解如何设置空字典的键和值。我已经有了它,但它不是正确的,我在网站上找不到任何有用的例子。有人可以向我解释如何做到这一点?请参阅下面的代码。谢谢。

class SetNumberOfRoomsPerFloor: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

//MARK: - Properties

@IBOutlet private weak var floorPicker: UIPickerView!

@IBOutlet private weak var numberOfRoomsPerFloor: UITextField!

private var managedObjectContext: NSManagedObjectContext!

internal var floorValue: Int16?

private var convertedFloorValues = [String]()

private var storedFloors = [Floors]()

private var pickedFloor: Int16?

private var roomNumberValue: Int16 {
    get {
        return Int16(numberOfRoomsPerFloor.text!)!
    }
}

private var floorsAndRooms = [String: String]()

override func viewDidLoad() {
    super.viewDidLoad()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    floorPicker.delegate = self
    floorPicker.dataSource = self
    loadFloorData()
    spinnerItems()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func setTheFloors(_ sender: UIButton) {
    if storedFloors.count > 0 {
        if storedFloors.first?.floorNumber == pickedFloor! {
            storedFloors.first?.numberOfRooms = roomNumberValue
            print("\(storedFloors.first?.floorNumber) + \(storedFloors.first?.numberOfRooms)")
        }
    }
}

private func setTheDictionary() { // this is not correct!
    for i in 0...storedFloors.count - 1 {
        floorsAndRooms.updateValue(String(describing: storedFloors.first?.numberOfRooms), forKey: String(i))
    }
    print("\(floorsAndRooms.count)")
}

@IBAction func nextStep(_ sender: UIButton) {

}

private func loadFloorData() {
    let floorRequest: NSFetchRequest<Floors> = Floors.fetchRequest()
    do {
        storedFloors = try managedObjectContext.fetch(floorRequest)
    } catch {
        print("could not load data from core \(error.localizedDescription)")
    }
}

private func spinnerItems() {
    for i in 0...floorValue! - 1 {
        convertedFloorValues.append(String(i))
}
// MARK: - Navigation

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

}



public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return convertedFloorValues.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return convertedFloorValues[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    print("\(convertedFloorValues)")
    let selection = Int16(convertedFloorValues[row]) // not sure I have to do this part.
    pickedFloor = selection
}

}

1 个答案:

答案 0 :(得分:1)

我认为这可能是您正在寻找的内容:

private static byte[] redimensionImage(ref byte[] photoBytes)
    {
        var byteCuantity = ConvertBytesToMegabytes(photoBytes.Count());
        ISupportedImageFormat format = new JpegFormat();

        using (MemoryStream inStream = new MemoryStream(photoBytes))
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                {
                    // Load, resize, set the format and quality and save an image.
                    using (var imageProcessor = imageFactory.Load(inStream))
                    {
                        var originalHeight = imageProcessor.Image.Size.Height;
                        var originalWidth = imageProcessor.Image.Size.Width;

                        //calculate aspect ratio
                        var aspect = originalWidth / (float)originalHeight;
                        int newWidth, newHeight;

                        var dimenssionTooSmall = false;
                        if (originalWidth <= originalHeight && originalWidth < 100)
                        {
                            //calculate new dimensions based on aspect ratio
                            newHeight = (int)(100 / aspect);
                            var resizeLayer = new ResizeLayer(new Size(100, newHeight), ResizeMode.Min);
                            imageProcessor.Resize(resizeLayer);
                            dimenssionTooSmall = true;
                        }
                        else if (originalHeight < originalWidth && originalHeight < 100)
                        {
                            //calculate new dimensions based on aspect ratio
                            newWidth = (int)(100 / aspect);
                            var resizeLayer = new ResizeLayer(new Size(newWidth, 100), ResizeMode.Min);
                            imageProcessor.Resize(resizeLayer);
                            dimenssionTooSmall = true;
                        }

                        if (byteCuantity > 1 || dimenssionTooSmall)
                        {
                            //format.Quality = 6;

                            imageProcessor.Resize(new ResizeLayer(new Size(3840, 2160), ResizeMode.Min));

                            imageProcessor.Format(format);
                            imageProcessor.Save(outStream);
                            return outStream.ToArray();
                        }
                        else
                        {
                            return inStream.ToArray();
                        }
                    }
                }


            }
        }
    }

您可能需要查看Apple's Swift Programming Guide。这很不错。控制流(用于迭代)和集合(用于词典)的部分应该非常相关。 (这是Swift 3版本的链接。)

另外,请注意,您没有为fetchRequest提供任何sortDescriptors。因此,您从CoreData获得的数组将不会按任何特定顺序排列,即它不会以楼层数的顺序排列。它确实没问题。您不需要对结果进行排序,因为您将它们存储在字典中,而字典中也没有排序。只要知道,当你检查所获取的数组时,它的元素就不会有序。