What's the correct syntax of copying a UIViewController? - swift2

I would like to copy an instance of a UIViewController.
Something like this:
gOriginViewController = self.copy() as! DiscoveryViewController
Which gives me the runtime error:
Bliss2.DiscoveryViewController copyWithZone:]: unrecognized selector sent to instance 0x7f8b4440cd70'
What's the correct syntax of doing a copy?

UIViewController does not implement NSCopying, and thus cannot be copied using copy(). You can use NSKeyedArchiver to do this:
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
let copy = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! DiscoveryViewController

Related

Ambiguous use of ‘subscript’ error when importing AVFoundation

Using Xcode 7.2 and Swift 2.1.1
I am retrieving data from a .plist file
The file contains data for a series of quizzes. The data for the quiz to be retrieved consists of an array of 12 questions and a corresponding array of 12 multiple choice options (4 members each).
var quizId = “”
var questions:[String] = []
var answers:[[String]] = []
The quiz id is passed in a segue from the previous view controller. Then the data is retrieved in ViewDidLoad.
let path = NSBundle.mainBundle().pathForResource(“quiz id”, ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
questions = dict!.objectForKey(“Questions”)![0] as! [String]
answers = dict!.objectForKey(“Answers”)![1] as! [[String]]
The code works perfectly well until I try to import AVFoundation, when the last two lines throw the ambiguous use of ‘subscript’ error.
This is because importing AVFoundation brings up new subscript definitions (namely AUAudioUnitBusArray, thank you Martin R.) and it confuses the compiler which doesn't know what type is dict!.objectForKey(“Questions”) anymore (it is indeed inferred as AnyObject after the import, instead of NSArray).
The cure is to safely help the compiler to know the type, for example by doing a downcast with optional binding:
if let questions = dict?.objectForKey("Questions") as? NSArray {
print(questions[0])
}
or even better:
if let questions = dict?.objectForKey("Questions") as? [String] {
print(questions[0])
}

How to assign one class type instance to another class type reference in swift to apply dynamic polymorphism

iam unable to set backgroundcolor for label at runtime
func example() {
let lbl: UILabel = UILabel()
let arrTemp: NSMutableArray = NSMutableArray()
arrTemp.addObject(lbl)
let tempButton: UIButton? = arrTemp.objectAtIndex(0) as? UIButton
tempButton.backgroundColor = UIColor.whiteColor()
}
Your logic is wrong for several reasons.
Let's see what you are doing
You are adding a UILabel to arrTemp.
arrTemp.addObject(lbl)
Now arrTemp does contain UILabel as only element
Next you retrieve the first element of arrTemp and try to cast it as UIButton.
let tempButton: UIButton? = arrTemp.objectAtIndex(0) as? UIButton
Of course the conditional cast will always fail (given the current code) and tempButton will be populated with nil.
You are accessing a property of tempButton (which is an Optional Value) without unwrapping it. The Swift compiled does not allow you to do this.
tempButton.backgroundColor = UIColor.whiteColor()
You could update the last line to make the compiler happy
tempButton?.backgroundColor = UIColor.whiteColor()
but the last assignment will never be executed since tempButton will always be nil.
Now a question: what are you trying to do? What do you want to achieve putting a UILabel into an array and then trying to use that label as a UIButton?
You can only reference the object as something it actually is. Otherwise, you could ask a label for its buttonType by using your untyped array without getting a compile-time error.
If you don't want that form of type safety, Objective-C is probably a better choice.
A UILabel is a subclass of UIView; a UIView has a settable property of backgroundColor. So, to set a UILabel color use simply:
func example() {
let lbl: UILabel = UILabel()
lbl.backgroundColor = UIColor.whiteColor()
// do something with lbl.
}

createFileAtPath not accepting NSURL anymore

let singleImage = "current.jpg"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(singleImage)
let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(path, contents: imageDataFromURL, attributes: [:])
createFileAtPath stopped working after upgrade to Swift 2 and now it gives the following error:
Cannot convert value of type 'NSURL' to expected argument type 'String'
Unfortunately NSFileManager has no creation method that operates on a NSURL. In my code I try to avoid String for path usage and this is one of the rare places I still fall back to a path using the NSURL.path property
fileManager.createFileAtPath(pathURL.path!, contents: imageDataFromURL, attributes: [:])

Cannot invoke initializer for type 'NSSet' with an argument list of type '(array: [NSData?])'

Getting this error when updating to swift 2.0:
Cannot invoke initializer for type 'NSSet' with an argument list of type '(array: [NSData?])'
I already do the searching but still can't fix it.
var object:UIImageView = UIImageView(frame: CGRectMake(0, 0, result.size.width, result.size.height))
object.image = UIImage(named: "image_default")
let element = NSEntityDescription.insertNewObjectForEntityForName("XKIMAGEVIEW", inManagedObjectContext: CoreDataUtil.sharedInstance.managedObjectContext!) as! XKIMAGEVIEW
element.image = NSSet(array:[UIImageJPEGRepresentation(object.image!, 1)])
the last line just have the error
seems like NSData couldn't be included in the array
Any idea of how to fix this issue?
UIImageJPEGRepresentation returns an optional, NSSet doesn't accept optionals.
Just unwrap the optional:
NSSet(array:[UIImageJPEGRepresentation(object.image!, 1)!])
Or, if the image representation could be nil use optional bindings
if let imageData = UIImageJPEGRepresentation(object.image!, 1) {
element.image = NSSet(array:[imageData])
}

Cannot subscript a value of type nsobject anyobject with an index of type String

I want to get name from google places using address dictionary in my xcode 7 project
Here is my code :
let name = placemark.addressDictionary["Name"] as? String
let city = placemark.addressDictionary["City"] as? String
let state = placemark.addressDictionary["State"] as? String
In otherwords NSObject and AnyObject are not subscript able with a string.
It's not the clearest message.
You might try NSString subscripts or you might not be able to use subscript syntax without more type info to tell Mr. compiler that your objects can respond to subscript syntax

Resources