ios開発中copyを利用して新しいオブジェクトを作成する方法

条件
User_Startnews24クラスを作成

1.User_Startnews24.h:
@interface User_Startnews24 : NSObject <NSCopying>{
NSString *name;
NSString *email;

}
@property (nonatomic, retain) NSString *name;
@property (nonatomic,retain)NSString *email;
@end

2.User_Startnews24.m
#import “User_Startnews24.h”
@synthesize name,email;
– (id)initWithName:(NSString *)theName andEmail:(NSString *)theEmail
{
self = [super init];
if (self){
self.name = theName;
self.email = theEmail;
}
}
– (id)copyWithZone:(NSZone *)zone
{
User_Startnews24 *aUser_Startnews24 = [[User_Startnews24 allocWithZone:zone] initWithName:[self name] andEmail:[self email]];
return aUser_Startnews24;
}
– (void)delloc
{
[name release];
[email release];
[super dealloc];
}

3.オブジェクトの間にcopy
①NSObjectを継承 ②<NSCoding>を実現 ③- (id)copyWithZone:(NSZone *)zone
4.NSArrayの間にcopy
例:
NSArray *array1 = [[NSArray alloc] initWithObjects:User_Startnews241,User_Startnews242,User_Startnews243,nil];
NSMutableArray *array2 = [array1 copy]; または
NSMutableArray *array2 =[ [NSMutableArray alloc] initWithArray:array1];

5.2つのメモリを利用する場合、NSArrayのdeep copyを呼び出す
例:
NSArray *array1 = [[NSArray alloc] initWithObjects:User_Startnews241,User_Startnews242,User_Startnews243,nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1 copyItems:YES];

IOS

Posted by arkgame