Objective-C magic path [9-class constructor and member variable scope, and variables], objective-c9-

Source: Internet
Author: User

Objective-C magic path [9-class constructor and member variable scope, and variables], objective-c9-

Master haomeng is devoted to his contribution and respects the author's Labor achievements. Do not repost them.

If the article is helpful to you, you are welcome to donate to the author, support haomeng master, the amount of donation is free, focusing on your mind ^_^

I want to donate: Click to donate

Cocos2d-X source code download: point I send


Constructor
To initialize the member variables in the class, you can provide a method for this purpose. This method is called a Constructor or Constructor ). Unlike C ++ and Java, Objective-C naming is unlimited and there is a type pointer of the returned value itself.
Take music as an example: Song. h file
@ Interface Song: NSObject {NSString * title; NSString * artist; long int duration;} // operation method-(void) start;-(void) stop;-(void) seek :( long int) time; // Method for accessing member variables @ property (nonatomic, retain) NSString * title; @ property (nonatomic, retain) NSString * artist; @ property (readwrite) long int duration; // constructor-(Song *) initWithTitle: (NSString *) newTitleandArtist: (NSString *) newArtistandDuration :( long int) newDuration; @ end
A method is added to the Song class definition. It is generally named starting with init. Its return value is special and is a type pointer of the return value itself. And there is a type pointer of the returned value itself.
The implementation code is as follows:
@ Implementation Song @ synthesize title; @ synthesize artist; @ synthesize duration; // constructor-(Song *) initWithTitle: (NSString *) newTitleandArtist: (NSString *) newArtistandDuration :( long int) newDuration {self = [super init]; if (self) {self. title = newTitle; self. artist = newArtist; self. duration = newDuration;} return self ;}...... @ end
Code Description:
1. The file imported by the header file reference rule must be enclosed by a pair of quotation marks, rather than the "<" and ">" characters in <Foundation/Foundation. h>. Double quotation marks apply to local files (files created by yourself) instead of system files, so that the compiler can find the specified files. 2. The implementation code of the constructor is almost the pattern code, which is basically written as follows:
-(Id) init {self = [super init]; if (self) {// initialization code} return self ;}
[Super init] is used to call the default constructor of the parent class.

The common programming habit of object initialization is that all initialization methods in the class start with init.

If you want to do something during class object initialization. You can override the init method to achieve this goal.

The instance object returned by this method is assigned to another New Keyword: self. Self is like this in C ++ and Java.
3. if (self) and (self! = Nil) to ensure that a new object is returned successfully when the parent class constructor is called. After the variable is initialized, return self to obtain its address.
4. Default parent class constructor-(id) init. Technically, the constructor in Objective-C is a method starting with "init", rather than a special structure in C ++ and Java.
5. The execution result of the parent class init method must be assigned to self, because the initialization process changes the position of the object in the memory (meaning that the reference will be changed ). If the initialization process of the parent class is successful and the returned value is non-null, it can be verified using the if statement. Note that the custom initialization code can be placed at the position of the code block. You can create and initialize instance variables at this location.

Note,

Init is defined as the return id type, which is a general rule for compiling init methods that may be inherited.

When the program starts execution, it sends the initialize call method to all classes.

If there is a class and related subclass, the parent class first obtains this message.

This message is sent only once to each class. Before sending any other messages to the class, ensure that the initialization message is sent to it.


Instance member variable scope qualifier

The instance variables declared in the interface can be inherited by subclass.

You can place the following command before the instance variable to control its scope more accurately:

Even from the encapsulation perspective, the instance member variables should be defined as @ private, but as an object-oriented language, Objective-C supports @ public, @ private, and @ protected scope restrictions. If an instance variable has no scope limitation, the default value is @ protected.
• @ Instance variables limited by the public scope can be directly accessed by methods defined in this class, other classes, or modules, and can be accessed under any circumstances;
• @ Private: The instance variables limited by the scope can only be accessed in this class. The instance variables defined in the implementation part belong to this scope by default.
• @ Protected: instance variables limited by the scope can be accessed in this class and in the derived subclass of this class. access outside the class is not recommended, but it can also be accessed. The instance variables defined in the interface section are of this scope by default. • @ Package: For a 64-bit image, you can access this instance variable anywhere in the image that implements this class.
The @ public command allows other methods or functions to access instance variables by using the pointer operator (->. But declaring instance variables as public is not a good programming habit, because it violates the idea of Data encapsulation (that is, a class needs to hide its instance variables ).

A simple example is used to describe the scope: Access is defined as follows:
#import <Foundation/NSObject.h>@interface Access: NSObject {@publicint publicVar;@privateint privateVar;@protectedint protectedVar;}@end
The main function called is as follows:
# Import <Foundation/Foundation. h> # import "Access. h "int main (int argc, const char * argv []) {Access * a = [[Access alloc] init]; a-> publicVar = 5; NSLog (@ "public var: % I \ n", a-> publicVar); a-> protectedVar = 6; NSLog (@ "protectedVar var: % I \ n ", a-> protectedVar); // cannot compile // a-> privateVar = 10; // NSLog (@ "private var: % I \ n", a-> privateVar ); return 0 ;}
Note: @ public, @ private, and @ protected limits only instance member variables that can be modified. They cannot modify class variables or methods.

What are class variables and class methods?

The following is a simple example:

ClassA. h file

#import <Foundation/NSObject.h>static int count;@interface ClassA: NSObject {int aaa;}+(int) initCount;+(void) initialize;@end

ClassA. m file

#import "ClassA.h"@implementation ClassA-(id) init {self = [super init];count++;return self;}+(int) initCount {return count;}+(void) initialize {count = 0;}@end

Code Description: The init method is the default constructor. In this constructor, the cumulative class variable count can be used in the instance method, but the class method cannot access the instance variable. The initCount method is a common class method used to return the class variable count. The initialize method is a very special class method that is automatically called when the class is accessed for the first time, therefore, it is generally used to initialize class variables, similar to the static constructor in C.

Main function called
#import <Foundation/Foundation.h>#import "ClassA.h"int main( int argc, const char *argv[] ) {ClassA *c1 = [[ClassA alloc] init];ClassA *c2 = [[ClassA alloc] init];// print countNSLog(@"ClassA count: %i", [ClassA initCount] );ClassA *c3 = [[ClassA alloc] init];NSLog(@"ClassA count: %i", [ClassA initCount] );[c1 release];[c2 release];[c3 release];return 0;}
Code Description:

When ClassA is instantiated for the first time, two methods are called:

Initialize class method and instance construction method init,

Then, when the ClassA is instantiated again, only the instance constructor init is called, instead of the initialize class method.
In this way, the class variable count is always accumulated and belongs to the class;

Therefore, the c1 instance can be accessed, and both c2 and c3 can be accessed.

Attributes, storage methods, and instance variables:

Encoding specification (Xcode4 already used) The current trend is to use the underscore (_) as the starting character of the instance variable name.

@ Synthesize window = _ window;

Indicates the value method and setting method of the synthesis (synthesize) attribute window,

And associate the property with the instance variable _ window (the instance variable is not explicitly declared.

This is helpful for distinguishing attributes and using instance variables.

[Window makeKeyAndVisible]; // Error

[_ Window makeKeyAndVisible]; // correct

[Self. window makeKeyAndVisible]; // correct


Global variables:

Compile the following statement at the beginning of the Program (all methods and class definitions:

Int gMoveNumber = 0;

The value of this variable can be referenced anywhere in this module.

In this case, gMoveNumber is defined as a global variable.

By convention, g in lower case is used as the first letter of the global variable.

An external variable is a variable that can be accessed and changed by any other method or function.

In the module that needs to access external variables, the variable declaration is the same as the normal method, but the keyword extern must be added before the declaration.


When using external variables, you must follow the following important principle: variables must be defined somewhere in the source file.

Declare variables outside all methods and functions without the keyword extern, for example, int gMoveNumber;

The second way to determine external variables is to declare variables outside all functions,

Add the keyword extern before the declaration and explicitly assign the initial value to the variable.


Remember, declarations do not cause memory space for Variable Allocation, but definitions will cause variable memory space allocation.

When processing external variables, variables can be declared as extern in many places, but can only be defined once.

Note: If the variable is defined in the file containing the access to the variable, the extern declaration is not required.


Static variables:

Variables defined outside the method are not only global variables, but also external variables.

If you want to define global variables that are global only in a specific module (file), you can use static to modify them.


Note that reloading alloc is not a good programming practice because this method processes the physical allocation of memory.


Enumeration data type:

The enumerated data type is defined starting with the keyword enum, followed by the name of the enumerated data type, followed by the identifier sequence (included in a pair of curly braces ), they define the allowed values that can be assigned to this type.

The scope of enumeration types defined in the Code is limited to the inside of the block.

In addition, the enumerated data types defined at the beginning of the program and beyond all blocks are global for this file.

When defining the enumerated data type, make sure that the enumerated identifier is different from the variable name and other identifiers defined within the same scope.


Objective-c Variables

Is that true?
@ Interface Member (){
UIImageView * ImageView;
}
@ End

@ Implementation Member

This variable is a class variable, but it is private. The scope is the current class. to be called by the outside world, you can only use interface functions, but cannot directly "."

Objective-Access to member functions and member variables in Class c

The method has no access level, which is similar to ObjectiveC and C (not C ++.
C defines the method, but if no declaration is given, other people cannot find it when calling it (although they can declare an identical method ). The same is true for ObjectiveC. No access protection level is available for all methods (@ property attribute is also a method)
There is only one access level, that is, the member variables defined in braces, which are public and private. It seems that there is no protected concept (maybe, but I don't need it at all ).
In ObjectiveC 2.0 or above, you rarely need to define your own member variables. The @ synthesize command can automatically generate a private member variable based on @ property.

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.