将一个NSString复制到另一个NSString

时间:2010-11-17 15:42:45

标签: iphone nsstring copy copywithzone

如何将一个NSString复制到另一个NSString?

@interface MyData : NSObject
{
    @private

    //user's private info
    NSInteger uID;
    NSString *name;
    NSString *surname;
    NSString *email;
    NSString *telephone;

    //user's picture
    UIImage *image;
}

@property (nonatomic, assign) int uID;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *surname;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *telephone;
@property (nonatomic, retain) UIImage *image;
@end

我有两个这种类型的对象。 MyData * obj1,obj2;

首先进行初始化。其次,我想首先初始化。

obj2 = [obj1 copy];   //crashes

    newData.surname = data.surname;   //crashes to
    newData.email = data.email;
    newData.telephone = data.telephone;

我认为第二个对象的副本没有保留!!!请帮忙!感谢名单!

3 个答案:

答案 0 :(得分:5)

您可以使用NSString方法stringWithString

请参阅also stringwithstring, what's the point?,了解何时可能只需为其提供相同的字符串。

答案 1 :(得分:4)

您的对象可能应该实现副本本身:

@implementation MyData

-(id)copyWithZone:(NSZone *)zone
{
    MyData *obj = [[[self class] alloc] init];
    obj.uID = self.uId;
    obj.name = self.name
    ...
    return obj;
}

....
@end

答案 2 :(得分:2)

将您的@属性更改为使用copy而不是retain:

@property (nonatomic) int uID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *surname;
@property (nonatomic, copy) NSString *email;
@property (nonatomic, copy) NSString *telephone;
@property (nonatomic, copy) UIImage *image;

请注意,您也不需要为uID分配。把这部分留下来吧。然后,您可以通过alloc轻松创建副本并初始化第二个MyData对象并分配属性:

MyData data = [[MyData alloc] init];
newData.surname = data.surname;   
newData.email = data.email;
newData.telephone = data.telephone;