#include <iostream>using namespacestd;intMain () {Charp[]={'a','b','C'}, q[]="ABC"; printf ("%d%d\n",sizeof(p),sizeof(q)); //getch ();}//result 3,4
What role does sizeof have?
sizeof is the C keyword is not not a function, this is easily ignored
sizeof (a) indicates the number of bytes in memory of a
The following is a 32-bit C + + program under Windows NT, please calculate the value of sizeof
void Func (char str[100])
{
sizeof (str) =?
}
void *p=malloc (100);
sizeof (p) =?
Answer: It's all 4 bytes.
But when I went to the interview, the meaning was written in 100;
Let's analyze:
Func (char str[100]) function in the array name as a function parameter, in the function body, the array name loses its own connotation, just a pointer, in the loss of connotation at the same time, he also lost the common characteristics, can be self-increment, self-reduction and other operations, can be modified. The length of the pointer (memory size) is 4 bytes under the Windows NT 32-bit platform, so sizeof (str) and sizeof (p) are 4
If it is under 64 bits, memory is 8 bits; 32-bit system is 4-bit
Cocoa Core Competencies object creation and iOS Test example: write an implementation of a NSString class
Build object requires 2 steps 1 Allocate memory, 2 initialize memory
1 Allocate memory, sent alloc or allocWithZone: message to the object's class. That's the common [Class alloc]. or uncommon [class Allocwithzone]
2 initialization. To initialize a method to invoke Init, a variety of init methods for or without parameters are counted.
The above object is created by the way that the return value is sent to the object to automatically manage the pool
example of an iOS face question: Write an implementation of a NSString class
+ (ID) initwithcstring: (constChar *+ (ID) stringwithcstring: (const Char*) nullterminatedcstring encoding: (nsstringencoding) encoding { NSString *obj; = [Self allocwithzone:nsdefaultmalloczone ()]; = [obj initwithcstring:nullterminatedcstring encoding:encoding]; return
The Form of an object-creation Expression
A convention in Cocoa programming are to nest the allocation call inside the initialization call.
Convenience function: Is the factory method, does not need the user management.
+ (ID
iOS app development: What is ARC?
ARC is a new feature of iOS 5, called arc (automic Reference counting). Simply put, the code is automatically added to the Retain/release, The code that originally needed to be manually added to handle the reference count of memory management can be automatically completed by the compiler.
The simple understanding of arc is that by making the syntax, the compiler (LLVM 3.0) automatically generates an instance of the reference count Management Section code when the code is compiled. At one point, arc is not a GC, he is just a static analyzer tool of code.
before and after the arc is used , we use code to implement
@interfaceNonarcobject:nsobject {nsstring*name; } -(ID) Initwithname: (NSString *) name; @end @implementationNonarcobject-(ID) Initwithname: (NSString *) NewName { self=[Super Init]; if(self) {name=[NewName retain]; } returnSelf ; } -(void) dealloc {[Name release]; [Super Dealloc]; } @end
@interface Arcobject:nsobject {NSS Tring *name; } -(id ) Initwithname: (nsstring *) name; @end @implementation Arcobject -(id ) Initwithname: (NSString * ) newName {self = [super Init]; if = NewName; return self; @end
When we used the memory management rules in objective-c, we often used the following guidelines
- When generating an object, use the Autorelease
- When the object is autorelease, first retain
- When an object returns in a function, use return [[object retain] autorelease];
With arc, we don't need to do this, even the most basic release.
What are the benefits of using arc?
What are the benefits of using arc?
- As you can see from the example above, it's easier to write objective-c code later, because we don't have to worry about annoying memory management and worrying about memory leaks.
- The amount of code has become less, looks refreshed, and saves Labor.
- Code is high-speed, reducing the likelihood of inefficient code by using the compiler to manage reference counts
Where's the arc bad?
- Remember a bunch of new arc rules-keywords and features that require a certain learning cycle
- Some old code, third-party code is more troublesome to use, modify the code requires work, or modify the compilation switch
On the 2nd, because the default arc in XCode4.2 is the state of on, there are often "Automatic Reference counting Issue" error messages when compiling old code.
At this point, you can set the "Objectice-c Auto Reference counteting" in the project compilation settings to No. as shown below.
If you only want to do not fit an. m file to arc, you can only add-fno-objc-arc to the file with the flags, such as.
The basic rules of ARC?
- Retain, release, Autorelease, dealloc are automatically inserted by the compiler and cannot be called in code
- Dealloc can be overloaded, but cannot be called [Super Dealloc]
Since ARC is not a GC and requires some rules to allow the compiler to support code insertion, it is important to be clear about these rules before you can write robust code.
Objective-c Object
Objects in Objectivec, with strong references (strong reference) and weak references (Weak reference), require retain to ensure object reference count plus 1 when other objects need to be persisted. As long as the object's holder (owner) exists, the object's strong references persist.
- This object can be used as long as the object's holder exists (the object is strongly referenced).
- When the object loses its holder, it is abandoned.
What is a strong reference (strong reference)?
(S1)
FirstName as the original holder of the "Natsu" string object, is the strong reference of the NSString type object.
-
(S2)
In this case, the FirstName is put into Aname, that is, Aname also becomes the holder of the @ "Natsu" string object, and Aname strong for that object.
-
(S3)
Here, change the content of FirstName. Generates a new string object "Maki". At this time FirstName become "maki" holders, and @ "Natsu" holders only aname. Each string object has its own owner, so they all exist in memory.
-
(S4)
Append the new variable othername, which will become another holder of the @ "Maki" object. That is, the strong reference of the NSString type object.
-
(S5)
Substituting othername into Aname, Aname will be the holder of the @ "Maki" string object. And the object @ "Natsu" has no owner, the object will be broken.
What is a weak reference (Weak reference)?
Let's take a look at how weak references (Weak reference) are used.
(W1)
As with strongly referenced methods, FirstName is present as a holder of the string Object @ "Natsu". That is, the strong reference of the NSString type object.
-
(W2)
Using the keyword __weak, declare the weak reference weakname variable, substituting the FirstName. At this time weakname although reference @ "Natsu", but still weak reference. That is, although weakname can see @ "Natsu", it is not its owner.
-
(W3)
FirstName points to the new object @ "Maki" and becomes its holder, while the object @ "Natsu" is abandoned because there is no holder. At the same time, the Weakname variable is automatically replaced with nil.
Reference keywords
Reference references to objects in arc, mainly with the following keywords. With strong, weak, autoreleasing-qualified variables are implicitly initialized to nil.
The variable declaration defaults to the __strong keyword, and if the variable does not write a keyword, then the default is a strong reference.
As seen above, this is a weak reference keyword. The concept is a new feature that starts importing from IOS 5/mac OS X 10.7. Because this type does not affect the life cycle of an object, if the object has no previous holder, there is a problem that has just been created, such as the following code.
NSString __weak *string = [[NSString alloc] Initwithformat:@ "firstName:%@", [ Self firstName]]; NSLog (@ "string:%@"string// This time string is empty
If the build setting OS version Deployment Target is set to this lower version, then the compile time will be an error (the current Deployment Target does not support automated __weak reference s), this time, we can use the following __unsafe_unretained.
A weak reference also has a feature that when a parameter object loses its owner, the variable is automatically paid nil (zeroing).
The keyword, like __weak, is also a weak reference, and the difference from __weak is simply whether to perform a nil assignment (zeroing). However, it is important to note that the object that the variable refers to has been broken, the address still exists, but the object in memory is gone. If you still access the object, it will cause a "bad_access" error.
The keyword makes the pair like a deferred release. For example, if you want to pass an uninitialized pair-like reference to a method that instantiates this pair of images in this method, you can use __autoreleasing. He is often used to deal with the return of function-valued parameters, such as the following example.
-(void) generateerrorinvariable: (__autoreleasing nserror * *) paramerror { .... *paramerror = [[Nserror alloc] Initwithdomain:@ "MyApp" code:1 userInfo: Errordictionary]; } .... { *error = nil; [Self generateerrorinvariable:&ERROR]; NSLog (@ "error =%@", error); }
Again, if the return value of a function is requested in a function, the following code is often expected when the release is on the caller's side.
-(NSString *) stringtest {nsstring *retstr = [NSString stringw Ithstring:@ " test " return [[Retstr retain] autorelease]; // use arc -(nsstring *) stringtest {__autoreleasing nsstring *retstr = [NSString alloc] Ini Twithstring:@ " " "; return Retstr; }
This keyword is used when the parameter of the method is id* and you want the object to be autoreleased when the method returns.
Summarize
-
Today, we see the basic ARC usage rules
- The code cannot use retain, release, retain, Autorelease
- Do not overload dealloc (the function can be overloaded if it is disposed of outside the object's memory, but cannot be called [Super Dealloc])
- Cannot use Nsallocateobject, Nsdeallocateobject
- Object pointers cannot be used in C struct bodies
- Between ID and void * If cast requires a specific method (__bridge keyword)
- Cannot use NSAutoreleasePool, but requires @autoreleasepool block
- You cannot use the name of a property that starts with "new" (If you use the following compilation error "Properties ' s synthesized getter follows COCOA naming convention for returning ' owned ' OBJEC TS ")
Original address: http://www.yifeiyang.net/development-of-the-iphone-simply-1/
IOS Face Test Summary