How do copy for UILabel? How do copy for UILabel? ios ios

How do copy for UILabel?


There is no public Apple API to deep copy a UILabel. Your best bet is to make a helper method which copies all the parts you care about.

- (UILabel *)deepLabelCopy:(UILabel *)label {    UILabel *duplicateLabel = [[UILabel alloc] initWithFrame:label.frame];    duplicateLabel.text = label.text;    duplicateLabel.textColor = label.textColor;    // etc... anything else which is important to your ULabel    return [duplicateLabel autorelease];}

If you want to use it all over your code base you can change it to a static method and put it in some sort of utility class. If you named the class LabelUtils you could do something like...

+ (UILabel *)deepLabelCopy(UILabel *)label {    // ...}

and would be called using UILabel *dupLabel = [LabelUtils deepLabelCopy:origLabel];


I recommend using a merged version of Answer 1 and Answer 2:

- (UILabel *)copyLabel:(UILabel *)label {    NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: label];    UILabel* copy = [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];    return copy;}

Then simply use something like

UILabel* labelcopy = [self copyLabel:originalLabel];

in your code.


UILabel does not conform to NSCopying, so you cannot make a copy via -copy.

But it does conform to NSCoding, so you can archive the current instance, then unarchive a 'copy'.

NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: label];UILabel *labelCopy =   [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];

Afterwards, you'll have to assign any additional properties that weren't carried over in the archive (e.g. the delegate) as necessary.