Simply using this way:
UIView* view2 = [view1 copy]; // view1 existed
This will cause simulator can not launch this app.
Try retain,
UIView* view2 = [view1 retain]; // view1 existed // modify view2 frame etc
Any modifications to view2
will apply to view1
, I understand that view2
share same memory with view1
.
Why can't UIView
be copied? What is the reason?
Retain increases the retain count of an object by 1 and takes ownership of an object. Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.
The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.
Luckily, there is a way around this. Since UIButton (which is a UIView ) can be archived, we can use NSKeyedArchiver and NSKeyedUnarchiver to create an NSData object representing our UIButton , and then de-serialize this object to get an identical duplicate of the original UIButton .
We can create a deep copy of the reference type using the copy() method. According to the documentation, copy() — Returns the object returned by copy(with:) . This is a convenience method for classes that adopt the NSCopying protocol.
this might work for you ... archive the view and then unarchive it right after. This should give you a deep copy of a view:
id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];
Your app probably crashes with something like:
[UIView copyWithZone:]: unrecognized selector sent to instance 0x1c6280
The reason is that UIView does not implement the copying protocol, and therefore there is no copyWithZone
selector in UIView.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With