2010-11-17 178 views
1

如何將一個NSString複製到另一個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; 

我neeeeed的第二個對象不保留一個COPY!請幫助!感謝名單!

+0

obj2實際上是一個MyData *?你需要MyData * obj1,* obj2; – Eiko 2010-11-17 15:45:33

+0

是的。這種相同類型的變量! – yozhik 2010-11-17 15:48:25

+0

MyData * obj1,* obj2;我只是忘記了asterix。 – yozhik 2010-11-17 15:49:00

回答

4

你的對象也許應該實現自身拷貝:

@implementation MyData 

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

.... 
@end 
+0

對象有不同的地址,但!!!! NSString對象具有EQUAL地址。我需要不同的地址。 – yozhik 2010-11-17 16:07:35

+0

然後你應該複製他們,使用 obj.name = [self.name複製] 等 – Romain 2010-11-17 16:15:27

+0

我試過 - >不幫 – yozhik 2010-11-17 16:18:59

2

更改@財產的使用副本,而不是保留:

@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; 
+0

這個變體不推薦在我的情況下使用。 – yozhik 2010-11-17 15:59:47