OC之Copy语法

2015-07-07  本文已影响370人  JaneJie
#import <Foundation/Foundation.h>
void test1()
{
  NSString *str = [NSString stringWithFormat:@"age is %i", 10];
  NSString *str1 = [str copy];
  NSLog(@"%i", str == str1);
  NSString *str2 = [str mutableCopy];
  NSLog(@"%i", str2 == str);
}
void test2()
{
  NSMutableString *str = [NSMutableString stringWithFormat:@"age is %i", 11];
  NSString *str1 = [str copy];
  NSMutableString *str2 = [str mutableCopy];
  [str appendFormat:@"1"];
  NSLog(@"%i", str == str2);
  NSLog(@"%i", str == str1);
  NSLog(@"%@", str);
  NSLog(@"%@", str1);
}
int main(int argc, const char * argv[])
{
  @autoreleasepool {   
    test2();
  }
  return 0;
}

四、对象拷贝的实例

对象的拷贝,主要注意点

1.必须实现NSCopying协议
2.需要重写- (id)copyWithZone:(NSZone *)zone方法

GoodStudent.h

#import "Student.h"
@interface GoodStudent : Student
@property (nonatomic, assign) int age;
+(id)goodStudentWithName:(NSString *)name withAge:(int)age;
@end

GoodStudent.m

#import "GoodStudent.h"
@implementation GoodStudent
+(id)goodStudentWithName:(NSString *)name withAge:(int)age
{
  GoodStudent *stu = [super studentWithName:name];
  stu.age = age;
  return stu;
}
-(id)copyWithZone:(NSZone *)zone
{
  GoodStudent *copy = [super copyWithZone:zone];
  copy.age = self.age;
  return copy;
}
-(NSString *)description
{
  return [NSString stringWithFormat:@"%@-%i", self.name, self.age];
}
@end

Student.h

#import <Foundation/Foundation.h>
@interface Student : NSObject <NSCopying>
@property (nonatomic, copy) NSString *name;
+(id)studentWithName:(NSString*)name;
@end

Student.m

#import "Student.h"

@implementation Student
+(id)studentWithName:(NSString *)name
{
  Student *stu = [[[[self class] alloc] init] autorelease];
  stu.name = name;
  
  return stu;
}

- (id)copyWithZone:(NSZone *)zone
{
  Student *copy = [[self class] allocWithZone:zone];
  
  copy.name = self.name;
  
  return copy;
}

-(NSString *)description
{
  return [NSString stringWithFormat:@"%@", self.name];
}

-(void)dealloc
{
  [_name release];
  [super dealloc];
}
@end

main.m

#import <Foundation/Foundation.h>
#import "GoodStudent.h"

void test1()
{
  Student *stu = [Student studentWithName:@"name1"];
  Student *stu1 = [stu copy];
  
  NSLog(@"%@", stu);
  NSLog(@"%@", stu1);
}

void test2()
{
  GoodStudent *stu1 = [GoodStudent goodStudentWithName:@"name1" withAge:10];
  
  GoodStudent *stu2 = [stu1 copy];
  
  NSLog(@"%@", stu1);
  NSLog(@"%@", stu2);
  
}

int main(int argc, const char * argv[])
{

  @autoreleasepool {
    
    test2();
    
  }
  return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读