1

I have a custom class which has got some properties. And I want to copy an object of this class so I get second object with the same content.
Example:

MyCustomClass *objectName = [[MyCustomClass alloc] init];
// fill here with some properties
objectName.propertyOne = @"smth";
objectName.propertyTwo = @"smth";
// And copy my object
MyCustomClass *secontObject = [objectName copy];

Does there exist something like "copy" method?

Note: the real copy method which is already built in didn't help.

jscs
  • 63,694
  • 13
  • 151
  • 195
Rendel
  • 1,794
  • 3
  • 13
  • 16
  • 2
    https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/ObjectCopying.html – pNre Apr 13 '14 at 18:46
  • In order for the `copy` method to give useful results you need to implement the `copyWithZone:` method in `MyCustomClass`. That will be called by `copy`. – rmaddy Apr 13 '14 at 18:51
  • possible duplicate of [the friendly documentation](https://developer.apple.com/library/mac/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCopying.html), found via [a search for "copying"](https://developer.apple.com/library/mac/search/index.php?Search=copying) in Apple's docs. – jscs Apr 13 '14 at 18:53

3 Answers3

2

There is nothing built in. The NSCopying protocol is included for this, but since it's just a protocol, you have to implement the copying logic yourself.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • Ok, It seems I should write this logic for every class which's objects I need to copy. Thanks. – Rendel Apr 14 '14 at 07:28
2

To use copy method you first need to implement NSCopying protocol for your custom class:

@interface SomeClass : NSObject <NSCopying> 

@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) NSNumber *number;

@end


@implementation SomeClass

- (id)copyWithZone:(NSZone*)zone
{
     SomeClass *copyObject = [SomeClass new];
     copyObject.string = _string;
     copyObject.number = _number;

     return copyObject;
}

. . . . . . .

@end
malex
  • 9,874
  • 3
  • 56
  • 77
1

You cannot make a copy of a custom class. You'll need to implement copy logic yourself.

See How to copy an object in objective c

Community
  • 1
  • 1
joels
  • 1,292
  • 15
  • 21
  • If you find another question that you believe answers this one, please flag the question for a moderator or vote to mark this as a duplicate rather than posting just a link. That allows solutions to a single problem to aggregate in one place, increasing their findability. – jscs Apr 13 '14 at 18:57
  • Thanks Josh. Will do in the future. – joels Apr 13 '14 at 19:14