copy one NSString to another
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;
}
@pro开发者_JAVA百科perty (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!
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.
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
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;
精彩评论