Home>

Tip:The "instance variables" mentioned in this article are "member variables", and "local variables" are "local variables"

Zero introductionarc is a new feature added since iOS 5.Eliminates the hassle of manually managing memory,The compiler will automatically insert the appropriate retain, release, and autorelease statements in the appropriate places. You no longer need to worry about memory management,Because the compiler handles everything for you

Note:arc is a compiler feature,Rather than the ios runtime feature (except the weak pointer system), it is not similar to the garbage collector in other languages.So arc and manual memory management performance is the same,Sometimes it can be faster,Because the compiler can also perform certain optimizations

First, the opening and closing of arcIf i want to convert non-arc code to arc code, there are about 2 ways:

(1). Use xcode's automatic conversion tool

(2). Manually set some files to support arc

1.Xcode's automatic conversion toolxcode comes with an automatic conversion tool,Can turn old source code into arc mode

(1) .arc is a feature of the llvm 3.0 compiler,The existing project may use the old gcc 4.2 or llvm-gcc compiler, so first you need to set up to use the llvm 3.0 compiler:

(Now using xcode4.5, llvm 3.0 has been upgraded to llvm 4.1)

It is best to select other warning flags in warnings as -wall so that the compiler will check all possible warnings.Help us avoid potential problems

(2) The run static analyzer option under build options is also best to enable,This way every time xcode compiles the project,Will run static code analysis tools to check our code

(3). Set the "objective-c automatic reference counting" option to yes, but the xcode automatic conversion tool will automatically set this option,Here is just how to set it manually

(4). Open Xcode's automatic conversion tool

(5) .xcode will display a new window,Lets you choose which files need to be converted

Click the check button, xcode may pop up a dialog box indicating that the project cannot be converted to arc, and you need to be ready to convert (the detailed description is omitted here for now)

(6) .If there are no warnings or errors, a prompt window will pop up:

(7). Click next, after a few seconds,xcode will prompt conversion preview of all files,Shows all changes to the source file.On the left is the modified file,On the right is the original file.Here you can view xcode changes on a file-by-file basis to ensure that xcode did not correct your source files:

Click save to complete the conversion

(8) .After automatic conversion,Xcode will remove all retain, release, and autorelease calls, which may cause other warnings, invalid syntax, etc. in the code.These need to be modified manually by yourself

Note:xcode's automatic conversion tool is best used only once,Repeated use may cause strange problems.If you didn't convert all files in the first conversion,When you later try to convert the remaining files again,xcode does not actually perform any conversion operations.So it is best to complete the conversion in one go,Files without conversion can be considered for manual modification

2, manually open the arc of some filesAdd -fobjc-arc to the compiler flags column to enable this.m file arc

3.Prohibit arc for certain files

Adding -fno-objc-arc to the compiler flags column disables this.m file arc

Second, the principlearc's rule is very simple:As long as there is one more variable pointing to the object,The object will remain in memory.When the pointer points to the new value,Or when the pointer no longer exists,The associated objects are automatically released.This rule applies to instance variables, synthesize attributes, and local variables.

Third, the strong pointerThere is a text input box property in the controller

</p>
<p>
@property (nonatomic, assign) iboutlet uitextfield * namefield;
</p>
<p>

1. If the user enters the string mj in the text box

Then we can say,The text property of namefield is a pointer to an nsstring object,The owner,This object holds the contents of the text input box

2. If the following code is executed

</p>
<p>
nsstring * name=self.namefield.text;
</p>
<p>

An object can have multiple owners,In the code above,The name variable is also the owner of this nsstring object.That is, there are two pointers to the same object

3. Then the user changed the content of the input box,such as

The text attribute of namefeild now points to the new nsstring object. But the original nsstring object still has an owner (name variable), so it will remain in memory

4. When the name variable gets the new value,Or when it no longer exists (such as when a local variable method returns or when an instance variable object is released), the original nsstring object no longer has any owner,The retain count drops to 0, at which point the object is released

For example, assign a new value to the name variable

name [email protected]"jake";
</p>
<p>

We call the name and namefield.text pointers "strong pointers" because they keep the object alive.All instance variables and local variables are strong pointers by default

Fourth, weak pointerWeak pointer variables can still point to an object,But not the owner of the object

1. Execute the following code

__weak nsstring * name=self.namefield.text;

Both the name variable and the namefield.text property point to the same nsstring object, but name is not the owner

2. If the content of the text box changes,The original nsstring object has no owner,Will be released,At this point, the name variable will automatically become nil, called a null pointer

It is very convenient for weak pointer variables to automatically become nil,This prevents the weak pointer from continuing to point to the released object,Avoid the creation of wild pointers,Otherwise it will lead to very difficult to find bugs, null pointers eliminate similar problems

3. The weak pointer is mainly used in the "parent-child" relationship. The father has a strong pointer for the son, so the father is the owner of the sonBut to stop the ownership cycle,The son needs to use the weak pointer to point to the father.The typical example is the delegate mode. Your viewcontroller has a uitableview through a strong pointer (self.view). The datasource and delegate of the uitableview are both weak pointers that point to your viewcontroller.

Five, the use of strong and weak pointers1. The following code is problematic:

__weak nsstring * str=[[nsstring alloc] initwithformat:@"1234"];
nslog (@ "%@", str);//prints "(null)"

str is a weak pointer, so the nsstring object has no owner,It will be released immediately after creation.xcode will also give a warning ("warning:assigning retained object to weak variable;object will be released after assignment")

2.General pointer variables are of the strong type by default, so generally we do not add __strong to strong variables. The following two lines of code are equivalent:

nsstring * name=self.namefield.text;
__strong nsstring * name=self.namefield.text;

3. The attribute can be strong or weak, written as follows

@property (nonatomic, strong) nsstring * name;
@property (nonatomic, weak) id delegate;

4. The following code may not work before arc,Because in manual memory management,When removing an object from nsarray,This object will send a release message and may be released immediately.Then nslog () prints the object and causes the application to crash

id obj=[array objectatindex:0];
[array removeobjectatindex:0];
nslog (@ "%@", obj);

This code is completely legal in arc,Because the obj variable is a strong pointer, it becomes the owner of the object,Removing the object from nsarray does not cause the object to be released

Six, arc summary1. With arc, our code can be much clearer,You no longer need to think about when to retain or release objects. The only thing to consider is the association between objects,Which object owns which object?

2.arc also has some restrictions:

1>First, arc can only work on objective-c objects. If your application uses core foundation or malloc ()/free (), you still need to manage memory manually

2>In addition arc has some other stricter language rules,To ensure that arc works properly

3. Although arc manages retain and release, it doesn't mean that you don't need to care about memory management at all.Because the strong pointer will keep the object alive,In some cases you still need to manually set these pointers to nil, otherwise it may cause the application to run out of memory.Whenever you create a new object,Need to consider who owns the object,And how long this object needs to survive

4.arc can also be used in combination with C++, which is very helpful for game development.For iOS 4, arc has a little limitation (weak pointers are not supported), but it doesn't matter too much

Seven, use of arc notice summary1. You cannot directly call the dealloc method, nor can you call the retain, release, autorelease, retaincount methods, including @selector (retain)

2. You can use the dealloc method to manage some resources,But cannot be used to release instance variables,The [super dealloc] method cannot be removed from the dealloc method. The dealloc of the parent class is also automatically completed by the compiler under arc.

3.Core foundation type objects can still use cfretain, cfrelease these methods

4. Can no longer use nsallocateobject and nsdeallocateobject objects

5. Object pointers cannot be used in c structures,If you have similar functions, you can create an objective-c class to manage these objects

6. There is no easy conversion method between id and void *,Similarly, conversions between objective-c and core foundation types require conversion functions specified by the compiler.

7. Can no longer use nsautoreleasepool object, arc provides @autoreleasepool block to replace it,This is more efficient

8. Cannot use memory storage area (can no longer use nszone)

9. Cannot name a property starting with new

10. Weak should generally be used when declaring iboutlets, except for the top-level objects in the middle of the nib such as storyboard.

11.weak is equivalent to the old version of assign, and strong is equivalent to retain

ios
  • Previous What are the integration methods of Spring and Mybatis
  • Next Query the data between the first few and the first few in the database in SQL SERVER SQL statement writing
  • Trends