I am not understanding how to give weak refrence to the array or release allocated memory of array, can anyone tell me how to fix this leak?
var menuDetails:[[String:Any]] = []//this my global array object
Getting following leak even i am using ARC.
Screenshot for array memory leak!
I was just scared about that memory leak,can anyone tell how do i fix it?
You don't want to use a weak reference. If you do that your array will get released immediately.
weak var weakArray: [[String:Any]]? = []
Will contain nil as soon as you create it.
Instead, you should set the array to nil (or empty) once you're done with the contents:
You could use `menuDetails.removeAll() to delete all the entries in the array, or you could change your declaration to make it an Optional
var menuDetails:[[String:Any]]? = []//this my global array object
And then set it to nil when you're done with it:
menuDetails = nil
An object will only be retained if another object has a strong reference to it. As soon as your view controller disappears, it will most likely be deallocated as well, which automatically removes its strong references to other objects. Thus, if imageArray is strongly referenced only by your disappearing view controller, the memory will automatically be released. You do not need to use an autoreleasepool.
In order to store weak references in arrays and/or dictionaries, you need an intermediate structure.
for example:
struct WeakRef
{
weak var object:AnyObject?
init( _ objectRef:AnyObject?)
{ object = objectRef }
}
// use WeakRef when you add object instances to your dictionary (or array)
menuDetails[0]["objectKey"] = WeakRef(yourObject)
// you will need additional code to get the actual object out of the intermediate structure
// and given that it is a weak reference you'll also need to deal with its optionality.
if let yourObject = (menuDetails[0]["objectKey"] as? WeakRef)?.object as? YourClass,
{
// ... do your thing with your object ...
}
The syntax could probably be made more legible by wrapping this in custom operators and generics but this is the general approach to it.
Related
I'd like to use a variable of type Any in order to pass different classes to a child view controller. For example, I might have Table, Chair and Plate objects. In my child view controller, I'd like to change the value of one of their properties (e.g. Table.legs was 4, change that to 3), and for the parent view controller to be able to read that from the child VC. I'll use a Protocol to update the parent VC that can pop the child after reading the updated object.
In order to work out how the passing of generics might work, I wrote this code in a playground:
class Table {
var legs: Int
var material: String
init(legs: Int, material: String) {
self.legs = legs
self.material = material
}
}
var anObject: Any?
// set up the Table
let aTable = Table(legs: 4, material: "Oak")
// set anObject to be the Table
anObject = aTable
// get the object and change it
let bTable = anObject as! Table
bTable.legs = 3
// get the original object and cast it as a Table
let cTable = anObject as! Table
print(cTable.legs) // prints 3
I believe from this, I should be able to do what I describe above without any issues, because the original object reference (anObject) is updated whenever I update a variable referencing it.
My question is this - are there any pitfalls I should be aware of when adopting this approach? It appears that rather than creating a copy of an object, swift will always create a pointer to the original object; are there any situations when that does not hold true?
Appologies if this is seen as a fairly basic question, but this is all fairly new to me - many thanks in advance!
Class are reference types as you noticed, if you assign an instance of the class to a variable, it keep the reference (the pointer in memory) to the instance and not the value copy.
Struct are value types, if you copy the instance of the structure to another variable, it's just copied to the variable.
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var _email: MaterialField!
#IBOutlet weak var _pass: MaterialField!
#IBOutlet weak var _signIn: UIButton!
#IBAction func attemptLoginWithEmail(sender : UIButton!) {
if let email = _email.text where email != "", let password = _pass.text where password != "" {
print(email)
}
}
Program keeps crashing , the _email.text and _pass.text keep returning nil. tried for a few hours but couldn't get it to work. any help would be appreciated
Just simply remove weak keyword from at the time of object preparation and now run your project its worked well.
Note :
A strong reference (which you will use in most cases) means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil will the object get destroyed (unless one or more other objects also hold a strong reference to it).
In contrast, with a weak reference you signify that you don't want to have control over the object's lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are:
1.) delegate properties, which are often referenced weakly to avoid retain cycles, and
2.) subviews/controls of a view controller's main view because those views are already strongly held by the main view.
I am not sure what it was but I deleted func attemptLogin and made another function exactly the same referring the same button and it worked. thanks for those of you who commented
When using Objective-C I would pass a NSMutableArray from one view controller VC_A to another VC_B by simply assigning a property in VC_B as
VC_B.list = self.list
where self is VC_A
It allows the changes done in VC_B on the list to be seen in the list in VC_A when the view controller was say popped off the navigation stack.
However in Swift as arrays are passed by value, assigning as above does not work so I am stuck how to solve this. What would be the correct way to handle this now?
You can still do this in Swift by making the property an NSMutableArray, just as before. Foundation types still exist if you ask for them. But this is bad design in both ObjC and Swift. It creates spooky action at a distance (when things magically change values that were not part of the call) and likely breaks MVC (if the data is persistent, it should live in the model, not in the view controllers).
There are two common patterns in Cocoa: store the data in the model, or pass it via delegation.
If this array represents some kind of persistent state (such as a list of items in the system), then that belongs in the model layer, and both view controllers should read and manipulate it there rather than by communicating with each other. (See Model-View-Controller.)
If this array is a transient piece of data (such as selections from a list), then the calling VC should set itself as the delegate to the receiving VC, and when the receiving VC finishes, it should pass the data back to its delegate. (See Delegates and Data Sources.)
If you use the standard Swift Array which is a value type you have to use a wrapper or a untyped NSArray.
// a generic wrapper class
class Reference<T> {
var value: T
init(_ val: T) { value = val }
}
// Usage
class ViewController1 {
static var list = Reference<[Int]>([])
}
class ViewController2 {
static var list = Reference([3, 5, 7, 9, 11])
func passToOtherVC() {
ViewController1.list = self.list
}
}
If you want to mutate the array you should always change the value property of the Reference object.
In Swift, objects are automatically passed by reference. NSArray is an Objective C class (pass by reference), where as Array is a struct (pass by value).
So if you are working with NSMutableArray the array is already being passed by reference.
Just as a potential proof of concept that complements my comment on the question - it is possible to use the Objective-C NSMutableArray to accomplish this task:
class A {
var x: NSMutableArray = NSMutableArray(capacity: 12)
}
class B {
var y: NSMutableArray!
}
let a = A()
let b = B()
b.y = a.x
b.y[0] = 123
assert(a.x[0] === b.y[0])
Still, this is approach is not following the Swift style of handling data structures IMO.
First q here, so trying to get protocol right...what I've done works, in that the data and views display correctly, but memory is not deallocating (still getting used to ARC after many years of allocating/deallocating), and I'm trying to figure out the right strategy. Document based app. When doc is created, view controller is instantiated, which creates several views which need to refer to each other for size/position/methods, and all of which need access to the doc data.
class MyDoc: UIDocument {
var data: Int
etc...
}
class MyController: UIViewController {
var doc: myDoc! // code which creates MyDoc instance assigns self to this property
var thisView1: MyView1!
var thisView2: MyView2!
thisView1 = MyView1(...)
thisView2 = MyView2(...)
thisView1.theOtherView2 = thisView2
thisView2.theOtherView1 = thisView1
thisView1.doc = self.doc
thisView2.doc = self.doc
}
class MyView1: UIView {
var theOtherView2: MyView2!
var doc: MyDoc!
}
class MyView2: UIView {
var theOtherView1: MyView1!
var doc: MyDoc!
}
I don't think I excluded anything meaningful. Assigning thisView1 and thisView2 to each other creates a strong reference cycle, right? I tried combining an unowned property on one with implicitly unwrapped on the other, per The Swift Programming Language, but kept having trouble with the init() methods of the views. Is using weak references and then unwrapping the optional all the time (though I make sure there's a valid value before proceeding from viewController) the only thing that'll work? I've read so many explanations that each new one now confuses me more.
Thank you!
I was playing with unowned references. As I understood from the WWDC videos, unowned references can't be nil, and they do not increase the retain count of whatever object they reference. I thought that if an unowned reference is deallocated, then the object that held the unowned reference is also deallocated.
Consider the following code:
class Parent {
var child : Child?
func foo() {
println("Hello")
}
}
class Child {
unowned let parent : Parent
init(parent: Parent) {
self.parent = parent
}
}
var parent : Parent? = Parent()
parent!.child = Child(parent: parent!)
weak var child = parent!.child
parent = nil
child!.parent.foo()
This code works! How come child exists, and moreover, how come parent apparently still exists? I had thought that after setting parent = nil, child would also be nil. It seems as if the unowned reference is acting as if it were a strong reference.
Any ideas as to why this code works?
Your code will most likely only work in the playground, where the memory management is a little... fuzzy.
When I ran this in Xcode, it crashes as you'd expect. The playground is meant to make it easy to test the syntax, play with some classes, etc. It's not the best place to play around with weak/unretained variables.
I haven't found any documented sources describing how exactly the memory is managed in a playground, but it's definitely different from how it will be in an actual runtime.