Keep an array from reinitializing

Here's my situation, I have a UIView that is "re-initialized" upon orientation change, and that effectively erases my var farPoints: [(point: CGPoint, type: CGPathElementType)] every time because of the way I have it initialize i believe. so, how can I init it in the init() function only if it's not nil... otherwise, I need a way to keep a variable from being reinitialized when a class is reinitialized.. makes sense? my farPoints contains an array of points I need to maintain when orientation is changed...

import Foundation
import UIKit
import AudioToolbox


class DrawView: UIView
{


    var lines: [Line] = []
    var lastPoint: CGPoint!
    var path = UIBezierPath()
    var currentLayer = CAShapeLayer()
    var savedPath = UIBezierPath()
    var farPath = UIBezierPath()
    
    var degreesOfRotation: CGFloat!
    var farPoints: [(point: CGPoint, type: CGPathElementType)]
    var tSize: CGSize!
    var drawn = false
    
    func DEGREESTORADIANS(_ degrees: CGFloat) -> CGFloat
    {
        return ((.pi * degrees)/180.0)
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.clipsToBounds = true
        self.contentMode = .scaleAspectFit
        
      if(self.farPoints == nil)
      {
        self.farPoints = []
        }
        degreesOfRotation = 0.0
   
        switch (UserDefaults.standard.integer(forKey: "rotate"))
        {
        case 1:
            degreesOfRotation = 0.0
            break
        case 2:
            degreesOfRotation = 90.0
            break
        case 3:
            degreesOfRotation = -90.0
            break
        case 4:
            degreesOfRotation = 180.0
            break
        default:
            degreesOfRotation = 0.0
            break
        }
        
        tSize = self.bounds.size
        
        if UserDefaults.standard.bool(forKey:"InvertColors")
        {
            self.backgroundColor = UIColor.white
            
            
            
            print("white")
        }
        else
        {
            self.backgroundColor = UIColor.black
            
            
        }
        path = UIBezierPath()
        
        
        // Custom decoding..
    }
    
    
    func convert_point(point: CGPoint) -> CGPoint
    {
        
        var toConvert = CGPoint()
        
      
    
            toConvert.x = (point.x - MyManager.shared().activeZone.origin.x ) / MyManager.shared().activeZone.size.width * tSize.width
            toConvert.y = (point.y - MyManager.shared().activeZone.origin.y) / MyManager.shared().activeZone.size.height * tSize.height
        
        
        
        toConvert = toConvert.rotate(around: self.bounds.center, with: degreesOfRotation)
       // boolPoint  = true
        print("CHECK TWO: \(toConvert) ")
        return toConvert
    }

    
    
    func move_began(point: CGPoint)
    {
        
         var newPoint = convert_point(point: point)
        path.move(to: newPoint)
        lastPoint = point
        
        setNeedsDisplay()
    }
    

    
    func move_moved(point: CGPoint)
    {
        var newPoint = convert_point(point: point)
        // lines.append(Line(start: lastPoint, end: newPoint))
        
        
        
        drawn = true
        path.addLine(to: newPoint)
        
        
        lastPoint = newPoint
        
        setNeedsDisplay()
    }
    
    
    func ended(point: CGPoint)
    {
        path.addLine(to: point)
    }
    
    
    
    
    
    override func draw(_ rect: CGRect) {
        /*  guard let context = UIGraphicsGetCurrentContext() else { return }
         
         
         context.beginPath()
         
         for line in lines {
         context.move(to: line.start)
         context.addLine(to: line.end)
         
         }
         
         
         context.setStrokeColor(UIColor.white.cgColor)
         context.strokePath()*/
        
        
        
        
        
        
        let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
        
        var pathR = UIBezierPath()
        
        pathR = UIBezierPath.init(cgPath: path.cgPath)
        
        
   //     pathR.apply(CGAffineTransform(translationX: center.x, y: center.y).inverted())
        pathR.apply(CGAffineTransform(rotationAngle: DEGREESTORADIANS(CGFloat(degreesOfRotation))))
     //   pathR.apply(CGAffineTransform(translationX: center.x, y: center.x))
        
        
        if(!UserDefaults.standard.bool(forKey: "DisableVibrations") && MyManager.shared()?.currentPage == DRAWING_MODE  && drawn )
        {
            print("vibrating")
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }
        
        
        currentLayer.contentsScale = self.contentScaleFactor
        
        currentLayer.frame = rect.standardized
    
        var pathNew = UIBezierPath()
        
        pathNew = UIBezierPath.init(cgPath: pathR.cgPath)
        if
            MyManager.shared()?.currentPage == DRAWING_MODE
        { pathNew = pathNew.fit(into: self.bounds).moveCenter(to: rect.center)

            
            farPath = UIBezierPath()
            farPath = UIBezierPath.init(cgPath: pathNew.cgPath)
        }
        
        
        if
            MyManager.shared()?.currentPage == DRAWING_MODE
        {
            currentLayer.path = farPath.cgPath
        }
        else
        {
            currentLayer.path = pathR.cgPath
        }
        
        if(UserDefaults.standard.bool(forKey: "InvertColors"))
        {
            self.backgroundColor = UIColor.white
            currentLayer.fillColor = UIColor.clear.cgColor
            currentLayer.strokeColor = UIColor.black.cgColor
        }
        else
        {
            
            self.backgroundColor = UIColor.black
            currentLayer.fillColor = UIColor.clear.cgColor
            currentLayer.strokeColor = UIColor.white.cgColor
        }
        currentLayer.lineWidth = CGFloat(UserDefaults.standard.float(forKey:"lineWidth"))
        currentLayer.contentsGravity = CALayerContentsGravity.bottom
        
        
        savedPath = UIBezierPath(cgPath: currentLayer.path as! CGPath)
        
        self.layer.addSublayer(currentLayer)
        
    }
    
    func a_point(point: CGPoint)
    {
     
     
        farPoints.append((point, CGPathElementType.addLineToPoint))
        print("hmm: \(farPoints.count)")

    }
    
    
    func b_point(point: CGPoint)
    {
        
        farPoints.append((point, CGPathElementType.moveToPoint))
        
    }
    
    func makeImage(with path: UIBezierPath, size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.black.setStroke()
        path.lineWidth = CGFloat(UserDefaults.standard.float(forKey:"lineWidth"))
        path.stroke()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    
    func SaveAndClear()
    {
        
        if(!drawn) { return }
        
        
        MyAwesomeAlbum.shared.save(image: makeImage(with: savedPath, size: self.bounds.size) as! UIImage)
        
        print("SHOULD SAVE")
        path = UIBezierPath()
        
        setNeedsDisplay()
        clear()
    }
    
    
    func clear()
    {
        
        
        path = UIBezierPath()
        
        farPoints = []
        
        setNeedsDisplay()
        
    }
    
    func adjust(TransitionTo tosize: CGSize)
    {
        path = UIBezierPath()
        setNeedsDisplay()
        
        
       
        tSize = tosize
        print("test: \(self.farPoints.count)")
        
        for i in 0 ..< farPoints.count {
            switch (farPoints[i].type.rawValue)
            {
            case 0:
                move_began(point: farPoints[i].point)
                
                
                break;
                
            case 1:
                move_moved(point: farPoints[i].point)
                
                break;
            case 2:
                break;
            default:
                break;
            }
        }
        
        
    }
    
}

Not really. What is "reinitialization"? Initialization is a specific thing that happens when an instance is allocated, tied to its lifecycle. Reinitialization is ...?

If you mean that (for some reason that isn't clear) the view is discarded (deallocated) on an orientation change and a new one created, then it's up to you to preserve the value somewhere. Indeed, the fact that the view is discarded is an indication that the array perhaps shouldn't be kept in the view at all. (Depending on what it represents, it might be better in the view controller, which presumably survives the orientation change, or conceivably even in your data model itself.)

Since your question is about views and — indirectly — about Cocoa design patterns, the question would perhaps be better asked and pursued over on forums.developer.apple.com.

Terms of Service

Privacy Policy

Cookie Policy