Copy of iOS

Source: Internet
Author: User

The object is in the heap, the heap is only responsible for the partition of the memory space, the memory space does not set its type, any type of pointer can point to this address, but the type of incompatible in Xcode will have a yellow warning.

The Copy method creates a copy of an object (usually a little more space), but there are exceptions to those objects that cannot be changed, such as the copy method of the NSString object, which does not open up new memory.

The Mutablecopy method is commonly used to create an immutable type object as a copy of a mutable type. Like what

NSString * str = @ "Hello";        nsmutablestring * StrM = [str mutablecopy];        [StrM appendstring:@ "123"];        NSLog (@ "%@", StrM);

The Copy method can not only be used for the type of OC, so long as the nscopying protocol is followed and the Copywithzone method is implemented, the custom object can be copied as well.

Person.h

#import <Foundation/Foundation.h> @interface person:nsobject <NSCopying> @property (nonatomic,copy) NSString * name; @property (Nonatomic,strong) nsnumber * age; @end

Person.m

#import "Person.h" @implementation person-(ID) Copywithzone: (Nszone *) zone{
/**
The reason for using the [self class] instead of the person is to facilitate inheritance, so if you are using the Copy method of the student object, the student object will be created.
*/person * p = [[[Self class] allocwithzone:zone]init]; P.name = Self.name; P.age = Self.age; return p;} -(NSString *) description{ return [nsstring stringwithformat:@ "%@:%p%@%@", [Self class],self, self.name,self.age] ;} @end

Student.h

#import "Person.h" @interface student:person@property (Nonatomic,strong) nsnumber * NO; @end

Student.m

#import "Student.h" @implementation student-(ID) Copywithzone: (Nszone *) zone{    Student * s = [Super Copywithzone:zone ];    S.No = self. No;    return s;} -(NSString *) description{    nsstring * str = [super description];    return [NSString stringwithformat:@ "%@%@", str,self. No];} @end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.