I made an NSObject
class that is receiving a couple of variables from a UIView
class. I am successfully receiving the variables in the NSObject
class and am processing them in my method receiveDims, where I append an array of Doubles. When I want to access this array in a second method (serialize), they show up as nil. Some of the research I have done on this suggest that this is a timing issue.
Does anybody have an idea as to why this is showing up as nil and not updating in serialize()? Is there a better way to have these arrays update in serialize()? Pertinent code is below.
class PostPath: NSObject {
var points:Array<PostPoint>
var color:UIColor
var width = [Double]()
var height = [Double]()
init(point:CGPoint, color:UIColor) {
self.color = color
self.points = Array<PostPoint>()
let newPoint = PostPoint(point: point)
points.append(newPoint)
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PostPath.receiveDims(_:)), name: "screenWidth", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PostPath.receiveDims(_:)), name: "screenHeight", object: nil)
}
func addPoint(point:CGPoint){
let newPoint = PostPoint(point: point)
points.append(newPoint)
}
func receiveDims(sender: NSNotification){
if sender.userInfo!["width"] != nil{
self.width.append(sender.userInfo!["width"] as! Double)
print("post path width \(self.width[0])")
}
if sender.userInfo!["height"] != nil{
self.height.append(sender.userInfo!["height"] as! Double)
print("post path height \(self.height[0])")
}
}
func serialize() -> NSDictionary{
print(self.width[0])
let dictionary = NSMutableDictionary()
let cgColor = color.CGColor
dictionary["color"] = CIColor(CGColor: cgColor).stringRepresentation
let pointsOfPath = NSMutableArray()
for point in points{
let pointDictionary = NSMutableDictionary()
pointDictionary["x"] = point.x!
pointDictionary["y"] = point.y!
pointsOfPath.addObject(pointDictionary)
}
dictionary["points"] = pointsOfPath
return dictionary
}
}
The class DrawingView is where the width and height variables originate. They are stored to NSNotificationCenter and PostPath.serialize() are called in the following manner (I have trimmed the code to only show these parts):
class DrawingView: UIView {
func getDims(){
self.width = Double(self.frame.size.width)
self.height = Double(self.frame.size.height)
NSNotificationCenter.defaultCenter().postNotificationName("screenWidth", object: nil, userInfo: ["width": width])
NSNotificationCenter.defaultCenter().postNotificationName("screenHeight", object: nil, userInfo: ["height": height])
}
func resetPatch(sendToFirebase:Bool){
currentPointPath?.serialize()
}
func addPathToSend(path: PostPath)->String{
firebaseKey.setValue(path.serialize()) { (error:NSError!, ref:Firebase!) -> Void in
if let error = error{
print("Error saving path to firebase\(error)")
} else{
pathsInLine.removeObject(firebaseKey)
}
}
return firebaseKey.key
}
}