代码之家  ›  专栏  ›  技术社区  ›  yozhik

将一个NSString复制到另一个NSString

  •  1
  • yozhik  · 技术社区  · 15 年前

    如何将一个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 回复  |  直到 15 年前
        1
  •  4
  •   Romain    15 年前

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

    @implementation MyData
    
    -(id)copyWithZone:(NSZone *)zone
    {
        MyData *obj = [[[self class] alloc] init];
        obj.uID = self.uId;
        obj.name = self.name
        ...
        return obj;
    }
    
    ....
    @end
    
        2
  •  5
  •   Community Mohan Dere    9 年前

    可以使用NSString方法 stringWithString .

    also stringwithstring, what's the point? 了解什么时候可能更倾向于给它相同的字符串。

        3
  •  2
  •   Ken Pespisa    15 年前

    将@property更改为使用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。把那部分去掉。然后,您可以通过分配和初始化第二个MyData对象并分配属性来轻松创建副本:

    MyData data = [[MyData alloc] init];
    newData.surname = data.surname;   
    newData.email = data.email;
    newData.telephone = data.telephone;
    
    推荐文章