1

How to copy one NSString to another?

@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

I have two objects of this type. MyData *obj1, obj2;

First is initialized. Second I want to initialize with first.

obj2 = [obj1 copy];   //crashes

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

I neeeeed a COPY of second object NOT RETAIN!!! Help please! Thanx!

yozhik
  • 4,644
  • 14
  • 65
  • 98

3 Answers3

5

you can use the NSString method stringWithString.

See also stringwithstring, what's the point? to understand when this might be preferred to simply giving it the same string.

Community
  • 1
  • 1
Alex Brown
  • 41,819
  • 10
  • 94
  • 108
4

your object should probably implement the copy itself:

@implementation MyData

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

....
@end
Romain
  • 4,080
  • 1
  • 18
  • 15
  • Objects has defferent addresses but!!!! NSString object has EQUAL addresses. I need differrent addresses. – yozhik Nov 17 '10 at 16:07
  • then you should copy them, using obj.name = [self.name copy] and so on – Romain Nov 17 '10 at 16:15
  • if you need a different address, you must create it yourself. Allocate your NSzone zone and then use it your copy obj2 = [obj1 copyWithZone:zone], and propagate in the copy method: -(id)copyWithZone:(NSZone *)zone{ ... obj.name = [self.name copyWithZone:zone] ... } – Romain Nov 17 '10 at 16:24
  • @ Romain previous comment: "obj.name = [self.name copyWithZone:zone]" this is a memory leak – user102008 Feb 22 '11 at 23:01
2

Change your @property's to use copy instead of 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;

Note that you also don't need the assign for the uID. Just leave that part out. Then you can easily create a copy by alloc and init-ing a second MyData object and assigning the properties :

MyData data = [[MyData alloc] init];
newData.surname = data.surname;   
newData.email = data.email;
newData.telephone = data.telephone;
Ken Pespisa
  • 21,989
  • 3
  • 55
  • 63