1

Sometimes copy is not implemented in some classes like in UILabel. A workaround would be to create another object and populate it with the attribute values of the original object.

For C# I found the MiscUtil library from Jon Skeet an Marc Gravell which provides a class called PropertyCopy.

Is there an equivalent (elegant) way to copy values of instancevariables in Objective-C?

At the moment I am doing it manually

myobject.attr1 = otherOBject.attr1;
myobject.attr2 = otherOBject.attr2;
...

but this is tedious and error prone.

Community
  • 1
  • 1
Aufwind
  • 25,310
  • 38
  • 109
  • 154
  • This sounds like a very error prone way to do copies itself. Think properties like `delegate` or `subviews`. – Nikolai Ruhe Jul 23 '12 at 16:59
  • @NikolaiRuhe I already stated myself, that it is error prone. Thanks for the examples for scenarios where it can get complicated, though. – Aufwind Jul 23 '12 at 17:03
  • I meant your proposal of copying all properties to be error prone. – Nikolai Ruhe Jul 23 '12 at 17:04
  • 1
    http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C – Sebastian Flückiger Jul 23 '12 at 17:07
  • You have to write to file and then load into a new object if you want a real copy of everything. – Dustin Jul 23 '12 at 17:11
  • When it gets tricky like this it's time to stop and think perhaps you're doing it wrong. Why do you want to copy UI objects like UILabel? You can subclass most objects and manage them this way, or use nibs to define given labels. Copying sounds like a bad way to go - perhaps you could say why it's the best way to go in your case? – ChrisH Jul 23 '12 at 17:57
  • @ChrisH, I am afraid, this will lead to far away from my question, but I'll try to explain to you why I (think) I need this. I have a UILabel view which is customized by the InterfaceBuilder (and StoryBoard) of Xcode. I need 2 duplicates of the same object outside the screen, to the right and to the left. They will hold other content. The goal is to be able to achieve the same effect like the homescreen navigation on the iPhone. To garantie, that the "homescreens" in my case "UILabels" are exactly the same I wanted to `copy` them, but this lead to an error. Hence my question. :-) – Aufwind Jul 23 '12 at 18:48
  • Everything you can do in IB you can do in code. So you could create your own UIButton class (or even customise it via a method) and then just create three of them in code. They would effectively be the same (other than the public attributes on the UILabel, I'm not sure what you would want to copy anyway). Your call, of course. – ChrisH Jul 23 '12 at 20:18

0 Answers0