开发者

Arguments for a copy method versus a copy constructor in Objective-C

开发者 https://www.devze.com 2023-04-10 03:06 出处:网络
I\'m relatively new to the world of Objective-C and have a class that I\'ve written to which I\'d like开发者_如何学Python to add the ability to create a copy.

I'm relatively new to the world of Objective-C and have a class that I've written to which I'd like开发者_如何学Python to add the ability to create a copy.

Coming from Java, I know that I could either write a copy constructor or a clone method, with the latter commonly not being recommended. However, Objective-C is a different language and before I proceed I'd like to understand the arguments for a copy method versus a copy constructor in Objective-C. What is the most commonly used approach?


The recommended way to add the ability to copy objects is by implementing the NSCopying protocol. Many foundation classes also implement NSCopying.

Refer to this answer for more information: Implementing NSCopying


Use: -(id)copyWithZone:(NSZone*)zone which is part of the NSCopying protocol

Example:

in .h:

@interface MyClass : NSObject <NSCopying>

in .m

-(id)copyWithZone:(NSZone*)zone {
    MyClass *copy = [[[self class] allocWithZone: zone] init];
    copy.user = self.user;
    copy.password = self.password;
//    etc

    return copy;
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号