Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To create a deep copy of UIImageView object you need to archive it using NSKeyedArchiver and then unarchive it with NSKeyedUnarchiver, but there is a problem with this approach because UIImage does not conform to the NSCoding protocol. What you need to do first is to extend the UIImage class to support NSCoding.</p> <p>Add a new category with name <code>NSCoding</code> on <code>UIImage</code> and place the following code:</p> <p><strong>UIImage+NSCoder.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface UIImage (NSCoding) - (id)initWithCoder:(NSCoder *)decoder; - (void)encodeWithCoder:(NSCoder *)encoder; @end </code></pre> <p><strong>UIImage+NSCoder.m</strong></p> <pre><code>#import "UIImage+NSCoder.h" @implementation UIImage (NSCoding) - (id)initWithCoder:(NSCoder *)decoder { NSData *pngData = [decoder decodeObjectForKey:@"PNGRepresentation"]; [self autorelease]; self = [[UIImage alloc] initWithData:pngData]; return self; } - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:UIImagePNGRepresentation(self) forKey:@"PNGRepresentation"]; } @end </code></pre> <p>Then add a new category with name <code>DeepCopy</code> (for ex.) on UIImageView and the following code:</p> <p><strong>UIImageView+DeepCopy.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface UIImageView (DeepCopy) -(UIImageView *)deepCopy; @end </code></pre> <p><strong>UIImageView+DeepCopy.m</strong></p> <pre><code>#import "UIImageView+DeepCopy.h" #import "UIImage+NSCoder.h" @implementation UIImageView (DeepCopy) -(UIImageView *)deepCopy { NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:self forKey:@"imageViewDeepCopy"]; [archiver finishEncoding]; [archiver release]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; UIImageView *imgView = [unarchiver decodeObjectForKey:@"imageViewDeepCopy"]; [unarchiver release]; [data release]; return imgView; } @end </code></pre> <p>Usage: Import your UIImageView+DeepCopy.h</p> <pre><code>UIImageView *imgView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picture.jpg"]]; UIImageView *imageView2 = [imgView1 deepCopy]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload