Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can UIView be copied?

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?

like image 258
Forrest Avatar asked Dec 13 '10 05:12

Forrest


People also ask

What's a difference between copy and retain?

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.

What is UIView in Swift?

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.

How do you duplicate a view in Swift?

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 .

How do I make a deep copy in Swift?

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.


2 Answers

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]]; 
like image 180
j2emanue Avatar answered Sep 24 '22 13:09

j2emanue


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.

like image 21
Engin Kurutepe Avatar answered Sep 21 '22 13:09

Engin Kurutepe