Briefly explain the basic characteristics of OBJECTIVE-C and its memory management mode _ios

Source: Internet
Author: User


A brief introduction of OC



OC language on the basis of C language, added a layer of minimal object-oriented syntax, fully compatible with the C language, in the OC code, you can mix C, or even C + + code.



You can use OC to develop applications for Mac OS X platform and iOS platform.



Development name: C language-.c OC language.-M compatible c++.-mm



Note: In fact, C language and OC even any language is just our to achieve some functions, to achieve some of the effects of the tool used, aside from the grammatical differences, I think the most important thing is to solve the problem when the angle and method is not the same, but this also constitutes the importance of learning a language.






Second, the grammar preview



(1) Key words



Basically all of the keywords are started with @ (to distinguish it from the keywords in c), such as @interface @implementation @public, and few don't start with @, like Id,_cmd






(2) string with @ start



C Language string: "Hello"



OC language string: @ "Hello"






(3) Other syntax



Basic type: 5 species, added boolean type



Nil is equivalent to NULL, which is 0.



Screen output: NSLog (@ "Hello");/Wrap Line



NSLog (@ "is%d", 2);






Iii. process of OC process development



#import The preprocessing directive has two functions: (1) As with #include, copying the contents of a file (2) can automatically prevent the contents of a file from being duplicated



Program Compilation Connection process:



Source (. m)---(compilation)----> Destination file (. 0)-----(link)----> executable (. Out)






Foundation Framework. What if you want to use all of the header files in the frame? Contains the primary header file for the frame. The primary header file is the primary header file in a frame, and the main header file name of each frame is the same as the frame name.



such as #import<foundation/foundation.h>



The running process is as follows:



(1) Writing OC source files. M. C



(2) Compile file cc-c xx.m xxx.c



(3) Link cc xx.o xxx.o-framework Foundation



(4) run./a.out






Iv. Types of Supplements


Copy Code code as follows:

Int Main ()


{

BOOL B=yes;

BOOL B1=no;

BOOL b2=1;//YES

BOOL b3=2;//NO

NSLog (@ "%i", b);

}






The bool type is consistent with other types of usage, and the nature of the bool type is a char type, defined as follows:


Copy Code code as follows:

Typedef signed Char BOOL

Macro definition:
Copy Code code as follows:

#define YES (BOOL) 1


#define NO (BOOL) 0


The output of a Boolean type is generally used as an integer.





Five, memory management
1. Basic principle



(1) Why the memory management.



Because the memory of mobile device is extremely limited, so the memory of each app is also limited, when the app occupies more memory, the system will issue memory warning, then need to recycle some memory space that does not need to continue to use, such as recycle some objects and variables that are no longer used.



Management scope: Any object that inherits NSObject is not valid for other basic data types.



The reason for this is that objects and other data types do not have the same storage space in the system, other local variables are mainly stored in the stack, and objects in the heap, when the code block at the end of the code block all the local variables involved will be reclaimed, the pointer to the object is also recycled, when the object has no pointer point, But it still exists in memory, causing memory leaks.






(2) The basic structure of the object



Each OC object has its own reference counter, an integer that represents the number of times the object is referenced, that is, how many things are currently using the object. When an object is first created, the default counter value is 1, and when the value of the counter changes to 0 o'clock, the object is destroyed.



Within each OC object, there is a special 4-byte storage space to store the reference counters.






(3) The role of reference counter



The only basis for determining whether an object should be recycled is if the counter is 0, or if it is not 0.






(4) Operation



Sends a message to an object and carries out counter actions accordingly.



Retain message: Make counter +1, change method return object itself



Release message: Make Counter-1 (does not represent free object)



Retaincount message: Gets the current reference counter value of the object






(5) Destruction of objects



When an object's reference counter is 0 o'clock, it is destroyed and the memory it occupies is reclaimed by the system.



When an object is destroyed, the system automatically sends an DEALLOC message to the object, typically rewriting the Dealloc method, releasing the relevant resources here, dealloc like the "Last words" of the object. Once you have overridden the Dealloc method, you must call [Super Dealloc] and place the last call to the code block (you cannot call the Dealloc method directly).



Once the object is reclaimed, the storage space that he occupies is no longer available, and persisting in use can cause the program to crash (wild pointer error).






2, related concepts and use of attention



Wild pointer error: Access to a bad memory (already recycled, unusable memory).



Zombie object: The object that the memory has been recycled, the zombie object can no longer be used. (Open Zombie Object detection)






Null pointer: No pointer to anything (the store is 0,null,nil), sending a message to a null pointer does not report an error



Note: You cannot use [P retaion] to bring a zombie object to a dead resurrection.






3, Memory management principles



(1) Principles



As long as someone is using an object, then the object will not be recycled;



As long as you want to use this object, then you should let this object's reference counter +1;



When you do not want to use this object, you should let the object's reference counter-1;



(2) who created, who release



(a) If you create an object through Alloc,new,copy, then you must invoke the release or Autorelease method



(b) You're not the one who created it.



(3) who retain, who release



As soon as you invoke retain, no matter how this object is generated, you will call release



(4) Summary



After the beginning, there should be a reduction in addition. Once let an object counter add 1, you should let it in the last-1.






4, Memory Management code specification



(1) If you call Alloc, you must have release (Autorelease)



(2) Code specification for the Set method



(a) Basic data type: Direct replication


Copy Code code as follows:

-(void) Setage: (int) Age


{

_age=age;

}


(b) OC Object type
Copy Code code as follows:

-(void) Setcar: (Car *) car


{

1. Decide if the new object is being passed in first.

If (Car!=_car)

{

2 One release for old objects

[_car release];//If there are no old objects, there is no effect

3. Make a retain for new objects

_car=[car retain];

}

}

(3) Code specification for Dealloc method

(a) Be sure to [Super Dealloc] and put it to the last

(b) Perform a release operation on other objects owned by self (current)

-(void) dealloc

{

[_car release];

[Super Dealloc];

}






5, the @property parameters



(1) Memory management related parameters



Retain: Release old value to object, Retain new value (for OC object type)



Assign: Direct Assignment (default, applicable to non-OC object type)



Copy:release old value, copy new value






(2) Whether the set method is to be generated (not generated if it is a read-only property)



Readonly: Read only, the Declaration and implementation of Getter are generated



ReadWrite: Default, generate both setter and getter declarations and implementations






(3) Multithreading management (Apple to some extent shielding the multithreading operation)



Nonatomic: High performance, general use of this



Atomic: Low Performance






(4) The name of the set and get methods



Modify the name of the set and get methods, primarily for the Boolean type. Because a method name that returns a Boolean type is typically preceded by an IS, modifying the name is generally used in the getter in the Boolean type.


Copy Code code as follows:

@propery (Setter=setabc,getter=isrich) BOOL rich;


BOOL b=p.isrich;//Call






6, memory management in the circular reference problem and solve



Case: Each person has an ID card, each ID card corresponds to a person, cannot use #import way to contain each other, this forms the circular reference.



New Keywords: @class class name;--Solve circular reference problem, improve performance



@class just tell the compiler to process the following name as a class when compiling.



(1) The role of @class: Declaring a class that tells the compiler that a name is a class



(2) Specification for referencing a class in development



(a) Use @class to declare classes in. h files



(b) Use #import to contain everything in a class when you really want to use it in the. m file



(3) The solution of circular reference at both ends



One end uses retain, one end uses assign (use assign in Dealloc without release)






7, Autorelease



(1) Basic usage



(1) The object will be placed in an automatic release pool



(2) When the automatic release of the pool is destroyed, the pool will be all the objects to be released once



(3) will return the object itself



(4) When the Autorelease method is called, the counter of the object is unaffected (affected by destruction)



(2) Benefits



(1) No need to care about the time of the release of the object



(2) No need to care about when to call release



(3) Attention to use



(a) Occupy large memory objects, do not use autorelease, you should use the release to accurately control



(b) Use of autorelease for objects with less memory, without much impact



(4) Wrong wording



(a) Continuous invocation of multiple autorelease, release of the pool when destroyed two releases (-1?) )



(b) The autorelease was invoked after the Alloc and then the release was called.



(5) Automatic release of the pool



(a) during the operation of the iOS program, countless pools are created that are present in the stack structure (advanced out).



(b) When an object invokes Autorelease, the object is placed in the release pool at the top of the stack



(6) How to create an automatic free pool



(a) Pre-iOS 5.0 creation method


Copy Code code as follows:

NSAutoreleasePool *pool=[[nsautoreleasepool alloc] init];


`````````````````

[Pool Release];//[pool drain]; for Mac


(b) After Ios5.0
Copy Code code as follows:

@autoreleasepool


{//Begin to create an automatic release pool

·······

}//end represents the destruction of an automatic free pool


(7) Autorelease Note





(a) in the system's own method, if the Alloc new copy is not included, the objects returned by these methods are autorelease, such as [NSDate Date];



(b) In development, some class methods are often written to quickly create a Autorelease object, instead of using the class name directly when creating the object, but using the self






8. ARC Memory Management mechanism



(1) Arc judgment criteria:



The object is freed as long as there is no strong pointer to the object.



(2) Pointer classification:



(a) strong pointer: By default, all pointers are strong pointers, keyword strong



(b) Weak pointer: _ _weak keyword decorated pointer



Declare a weak pointer as follows:


Copy Code code as follows:

_ _weak person *p;

In arc, the weak pointer is emptied directly as long as the weak pointer points to an object that is not present.
Copy Code code as follows:

_ _weak person *p=[[person alloc] init];//unreasonable, the object is created to be released, the object released, arc the pointer automatically clear zero.

In the arc, the retain is no longer used in the property, but the strong is used, and no more [super Dealloc] is needed in the dealloc.





The @property (nonatomic,strong) Dog *dog;//means that the generated member variable _dog is a strong pointer, equivalent to the previous retain.



If replace is weak pointer, then change weak, do not need to add _ _.






(3) Summary of the characteristics of arc:



(a) Not allowed to invoke Release,retain,retaincount



(b) Rewriting of dealloc is not allowed, but calls to [super Dealloc] are not allowed



(c) Parameters of the @property:



Strong: Equivalent to the original retain (for OC object type), member variable is strong pointer



Weak: Equivalent to the original assign (for OC object type), member variable is weak pointer



Assign: Applicable to non-OC object types (underlying type)



(4) Supplementary



Make the program compatible with ARC and non-arc parts. Transformed into a arc-fno-objc-arc,-f-objc-arc, converted to arc.



ARC also needs to consider circular reference problems: one end uses retain and the other end uses assign.






Tip: Strings are special objects, but they do not need to be released manually, and this string object is autorelease by default, without extra memory to be used.


Related Article

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.