1

如何将一个 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

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

首先是初始化。其次,我想先初始化。

obj2 = [obj1 copy];   //crashes

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

我需要不保留第二个对象的副本!!!请帮忙!谢谢!

4

3 回答 3

5

您可以使用 NSString 方法stringWithString

另见stringwithstring,有什么意义?了解何时可能比简单地给它相同的字符串更可取。

于 2010-11-17T15:51:18.453 回答
4

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

@implementation MyData

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

....
@end
于 2010-11-17T15:50:30.420 回答
2

更改您的@property 以使用复制而不是保留:

@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。把那部分留在外面。然后,您可以通过分配和初始化第二个 MyData 对象并分配属性来轻松创建副本:

MyData data = [[MyData alloc] init];
newData.surname = data.surname;   
newData.email = data.email;
newData.telephone = data.telephone;
于 2010-11-17T15:56:15.423 回答