Objective-c syntax (4), objective-c syntax
String in oc
Quickly create strings (the simplest method)
NSStirng * str = @ "Hello"; // oc strings are in the form @ ""
The oc string is also a Class Object and is an NSString class object. It is not so troublesome to create it. [] use the object-oriented idea to manipulate the string.
Char * name = "xxxxx"; // c-style string
Oc uses % @ output string, not % s
NSString * name = @ "dashuai"; NSLog (@ "My name is % @", name );
The usage of c-style string output Parsing is % s.
NSLog (@ "% s", name); // % s is a c-style format parsing
Another method of OC string, the NSString class in the Foundation framework
NSString *newStr = [NSString stringWithFormat:@"My age is %d and no is %d and name is %@", age, no, name];NSLog(@"---- %ld", [newStr length]);
The length method returns the unsigned long type.
NSString * name = @ "Haha reaches"; // The length method calculates the total number of words, including the number of words! Not the number of characters !! Int size = [name length];
Query the document if you do not understand it! Baidu!
// Main. m # import <Foundation/Foundation. h>/* NSString: unchangeable string NSMutableString: Variable string */int main () {NSMutableString * s1 = [NSMutableString stringWithFormat: @ "my age is 10"]; // splice the content to the end of s1 [s1 appendString: @ "11 12"]; // obtain the is range: nsange range = [s1 rangeOfString: @ "is"]; [s1 deleteCharactersInRange: range]; NSString * s2 = [NSString stringWithFormat: @ "age is 10"]; // create a new string and splice it into the new string, but the original string has not changed! The two methods are different. NSString * s3 = [s2 stringByAppendingString: @ "11 12"]; NSLog (@ "s1 =%@, s2 =%@", s1, s2); return 0 ;} void stringExport () {// export string [@ "Jack \ nJack" writeToFile: @ "/Users/apple/Desktop/my.txt" atomically: YES encoding: NSUTF8StringEncoding error: nil]; NSString * str = @ "4234234"; NSURL * url = [NSURL fileURLWithPath: @ "/Users/apple/Desktop/my2.txt"]; [str writeToURL: url atomically: YES encoding: NSUTF8StringEnc Oding error: nil];} void stringCreate () {/* 1. create a string */NSString * s1 = @ "jack"; // NSString * s2 = [[NSString alloc] initWithString: @ "jack"]; this method is not recommended! NSString * s3 = [[NSString alloc] initWithFormat: @ "age is % d", 10]; // C string --> OC string NSString * s4 = [[NSString alloc] initwithuf8string: "jack"]; // OC string --> C string const char * cs = [s4 UTF8String]; // NSUTF8StringEncoding can be used in Chinese to encode NSString * s5 = [[NSString alloc] initWithContentsOfFile: @ "/Users/apple/Desktop/1.txt" encoding: NSUTF8StringEncoding error: nil]; // URL: Resource path // protocol header: // path // local file: /// ftp: // web resource http://weibo.com/a.png // http://www.baidu.com // NSURL * url = [[NSURL alloc] initWithString: @ "file: /// Users/apple/Desktop/1.txt"]; NSURL * url = [NSURL fileURLWithPath: @ "/Users/apple/Desktop/1.txt"]; NSString * s6 = [[NSString alloc] initWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil]; NSLog (@ "s6 = \ n % @", s6 ); /* generally, a class method is paired with an object method [NSURL URLWithString: <# (NSString *) #>]; [NSString stringWithFormat: @ ""]; [NSString stringWithContentsOfFile: <# (NSString *) #> encoding: <# (NSStringEncoding) #> error: <# (NSError * _ autoreleasing *) #>]; */}
Set and get methods of OC
The member variables of the class should not be @ public as far as possible to ensure data concealment and encapsulation. It is not recommended to directly use member variables of the class using objects, because such member variables of the class can be modified at will, it is not safe, but should be called indirectly. In addition, direct calls will allow others to immediately see the internal structure and information of the class, without the meaning of encapsulation.
Set Method
1) function: Used to set member variables. Some unreasonable values can be filtered out in the method.
2) Naming rules:
- The method names start with set and follow the name of the member variable. The first letter of the member variable name must be capitalized.
- The parameter must be accepted, and the parameter name must not have the same name as the member variable.
- Return Value void
Get Method
1) function: return the member variables in the object.
2) Naming Convention: The get method name is generally the same as the member variable name.
/* Naming rules for member variables: start with an underscore _ @ interface Student: NSObject {1. separate member variables from the names of the get method. it can be separated from local variables. Variables starting with an underscore are generally member variables */int _ no; Sex _ sex ;} // set and get methods of sex-(void) setSex :( Sex) sex;-(Sex) sex; // set and get methods of no-(void) setNo :( int) no;-(int) no; @ end
Oc-compatible with the point syntax of the c series
The dot syntax can be used to replace the oc odd object call form. This is an oc-specific practice that allows programmers (mainly programmers who are used to c series programming languages, such as c, c ++, and java) to quickly understand.
// The essence of the Point syntax is the method call p. age = 10; // [p setAge: 10];
It is still odd here. Whether it is the get or set method depends on whether it is assigned a value (set) or a value (get ). It is also different from the point Syntax of java or c ++.
The role of class member variables in oc
@ Public: You can directly access the member variables of an object anywhere.
@ Private: It can only be accessed directly in the object method of the current class. Private Members can only be directly accessed in this class. The subclass is invisible and can only be accessed by the set and get methods (@ implementation is @ private by default, because the implementation file is generally not included, all include header files, so the implemented files are private by default)
@ Protected: You can directly access the object method of the current class and its subclass (@ interface is @ protected by default)
@ Package: the member variables of the object can be directly accessed as long as they are in the same framework.
@ Interface and @ implementation cannot declare member variables with the same name. Conflict with the same name is very understandable.
A feature of Xcode: @ property and @ synthesize
S then n θ then sa then zVSynthesis; (chemical or biological) synthesis; (audio) Synthesis
@ Property
Automatically generate the set and get methods, similar to the java eclipse setter and getter options
# Import <Foundation/Foundation. h> @ interface Person: NSObject {int _ age; int _ height; double _ weight; NSString * _ name;} // @ property: can only be used in Declaration, the setter and getter declarations of a member variable can be automatically generated and different from those of java. xcode hides the automatic declaration and is invisible. This is a feature of the compiler! The following sentence represents the two comments. @ Property int age; //-(void) setAge :( int) age; //-(int) age; @ property int height; // set mr and then get //-(void) setHeight :( int) height; //-(int) height;-(void) test; @ property double weight; // if the member variables have the same type, they can be merged and written together, but the actual development is not like this. It is better to separate them @ property NSString * name; @ end
Note: If the variable age in @ property is not declared in advance, it can also be run. The compiler will automatically generate the _ age member variable, which is available after xcode4.4. The generated member variable is @ private in the class declaration. If this member variable is stored in the class declaration, if @ property is still written, it will not be automatically generated.
@ Synthesize
Write it only in the implementation. You can automatically find @ property in the class declaration, and then generate the setter and getter methods of the class member variables based on it, and access this member variable.
@ Synthesize age = _ age;
In this case, the age member variable is accessed by default. If no age exists, the @ private type age variable is automatically generated, which is automatically included in the class declaration.
Note: After xcode4.4, in order for programmers to focus on business logic rather than unnecessary spam code writing, xcode becomes more convenient and more things are done, now, the declaration of member variables of the class can be omitted. Directly @ property can automatically generate the declaration of variables and the related set and get methods. Similarly, @ synthesize does not need to be written in the class implementation after 4.4. That is to say, the implementation of set and get does not need to be written.
It means that the @ property declaration in the current @ property declaration does two things by default, that is, the declaration of "set" and "get" is generated, and the implementation of "set" and "get" is also generated. Of course, if there is no variable declaration in the class declaration, the third thing is to automatically generate private member variables.
The Xcode principle is: No. I will generate it for you and use it directly if I have it.
Here, we can explain why the member variables of the apple suggestion class are prefixed with underscores?
Because of the new features of @ property: Since xcode4.4, @ property has exclusive features of @ synthesize. That is to say, @ proeprty can generate a set of member variables at the same time, the get method can be both declared and implemented. By default, the implementation of the set and get Methods accesses member variables of the underline. Therefore, it is required that the member variables be named using the variable naming method of the underline in the declaration of the class. In the end, it is because the new @ property feature automatically generates the set and get method declaration and implementation. By default, all member variables with underlines are accessed.
Id type in oc (Universal pointer)
Id is a type
The type cannot be a variable name, such as an int. It is incorrect.
Id is a universal pointer
Can point to (manipulate) Any oc object, and can not add *, write id represents the pointer (because the id already contains *, see the official documentation ).
Person * p = [Person new]; // the object of the traditional operator. The Person type pointer p points to the Person's object.
Universal pointer. id can point to or to operate any OC object. It is only applicable to oc objects.
Id d = [Person new]; // id indicates the object of a Person
Disadvantages of id:
If it also points to an object method that does not exist in the (called) class, the compiler will directly report an error! No weak syntax
Never add *
Oc constructor and rewriting
Constructor: the method used to initialize an object. In oc, it is an object method, starting with-init.
Object-oriented languages include the constructor method, which is similar to the new class method in c ++ to create objects.
// Person * p = [Person new]; it is not recommended to create an object like this
New is actually a class method. It is a NSObject class method that can create objects and allocate memory. But in fact, we are not commonly used because it is too rigid and monotonous to do things, is to create a complete available object.
You can create an available object in two steps:
1. Allocate storage space + alloc
2. initialize-init
The new method performs these two tasks. Inside the new method, two methods (one class method and one object method) are called to complete this step. The details are as follows:
1. Call + alloc to allocate storage space
Person * p1 = [Person alloc]; // The object is unavailable at this time, and no Initialization is performed. The id (oc object) is returned)
2. Call-init for initialization
Person * p2 = [p1 init]; reverse oc object (after initialization) itself
It indicates that new is the combination of two methods, which are not commonly used in development and rigid. Generally, two steps are taken. The consequence is convenient selection. Because Initialization is not necessarily the initialization of the init object method ..
The two-step merge method is simple: Master, and this method is often used in development, so no new is needed.
Person *p4 = [[Person alloc] init];
The Oc constructor is the-init method, which is used to initialize objects. Object method. The member variables in each object are initialized to 0 by default,
Create a person object to ensure that all her _ age values are 10 by default, not 0. How can this problem be solved?
Override the-init method to overwrite the parent class-init method.
Purpose of rewriting constructor:
To create an object, the member variables have fixed values.
Notes for rewriting Constructor
1. First call the constructor of the parent class ([super init])
2. initialize the member variables in the subclass, which is similar to c ++.
Person. h # import <Foundation/Foundation. h> @ interface Person: NSObject @ property int age; @ endPerson. m # import "Person. h "@ implementation Person // rewrite-init method. In fact, the id is similar to the c ++ template application. //-(Id) init // {// 1. You must first call the super init method: initialize some member variables declared in the parent class and other attributes self = [super init]; // The current oc object is returned, which must be accepted by self. You need to study it here, crowdsourced security testing. // 2. if the parent class object is initialized successfully, it is necessary to perform subsequent initialization // if (self! = Nil) // {// _ age = 10; //} // 3. return an initialized oc object // return self ;//}
// Write the statement as follows:-(id) init {if (self = [super init]) {_ age = 10;} return self ;}@ end
Requirements:
Student object. After initialization, the student IDs are all 10, and the student IDs are all 1. Or rewrite the constructor-init.
Student. h inherits the person class # import "Person. h" @ interface Student: Person @ property int no; @ end
Student. m # import "Student. h "@ implementation Student // After the Student object initialization is complete, the age is 10, and the Student id is 1-(id) init {if (self = [super init]) {_ no = 1;} return self;} @ end
Main. h # import <Foundation/Foundation. h> # import "Person. h "# import" Student. h "int main () {// each stu object is created. Its _ age value is 10, the student ID is 1, and isa points to each p4 object, her _ age is 10, and isa points to its class Person * p4 = [[Person alloc] init]; Student * stu = [[Student alloc] init]; return 0 ;}
Student inherits person, while person inherits NSObject. For example, the student object contains three member variables: student's own _ no, and the _ age inherited from the parent class person class, and the isa pointer of the parent class NSObject inherited from the person class at the very beginning. These three member variables are all contained by the student object stu!
This is because when the student class creates a student object, it first enters the student class lookup-init (because oc stipulates that if the parent class and the subclass have a method with the same name, the subclass object first calls the method with the same name as the subclass), and then finds the-(id) init method in the student class, and then finds:
{If (self = [super init]), the compiler will first enter the parent class person, because super serves {_ no = 1;} return self ;}
Then, call the-init of the directly parent class person, and the-init of person is:
-(Id) init {if (self = [super init]) is still executed here. We find that debugging cannot be performed because super calls NSObject and apple is not open-source, however, the fact still goes in and steals the NSobject-init method, initializes the isa pointer, and initializes isa to point to the student class itself. Remember that it is the current class. After Initialization is complete, the program is executed back to the person class, continue to execute _ age = 10. (At the same time, student's member variable age becomes 10) {_ age = 10;} return self; finally, the returned self points to the current student object}
After the-init of person is called, The system returns to the student class of the subclass. It continues to execute the-init of student and runs _ no = 1. The inherited isa class is initialized to its student class, this completes initialization.
When the person object is initialized, similarly, first find the initialization method in this class, find the super statement, and then find the-init method in the NSObject class of the parent class, (Remember the Writing Method of self = [super init] first, and then go into depth.) NSObject is to initialize isa and point isa to the person class, (pointing to the current class, this class is full source and cannot see the internal code) then return to the person class, _ age = 10. The execution is complete.
Let's take a look at the student object. initialize the object first when it is created. Similarly, in this class, super is found. Then, execute-init in the parent class person and find super, execute-init in NSObject, point isa to the student class itself, (the current class is not person, it is student), and return to person, _ age = 10. return to student, _ no = 1. After execution, return to the main function, initialize, and complete.
Custom oc Constructor
Oc custom constructor Specification
1. It must be an object method, so it must start-
2. the return value is generally of the id type.
3. method names generally start with initWith
This reminds me that the construction of the c ++ constructor with parameters and default constructor is similar to that without parameters. It is actually a construction with parameters. Similar to c ++.
Person. h # import <Foundation/Foundation. h> @ interface Person: NSObject @ property NSString * name; @ property int age;-(id) initWithName :( NSString *) name;-(id) initWithAge :( int) age; -(id) initWithName :( NSString *) name andAge :( int) age; @ endPerson. m # import "Person. h "@ implementation Person-(id) initWithName :( NSString *) name {if (self = [super init]) fixed syntax, remember {_ name = name;} return self ;} -(id) initWithAge :( int) age {if (self = [super init]) {_ age = age;} return self;}-(id) initWithName :( NSString *) name andAge :( int) age {if (self = [super init]) {_ name = name; _ age = age;} return self ;}@ endStudent. h inherits the person class # import "Person. h "@ interface Student: Person @ property int no; // _ no is the attributes of student (id) initWithNo :( int) no;-(id) initWithName :( NSString *) name andAge :( int) age andNo :( int) no; @ endstudent. m # import "Student. h "@ implementation Student-(id) initWithNo :( int) no {if (self = [super init]) {_ no = no;} return self ;} // understand and accept this practice and idea: // the attributes of the parent class are handed over to the parent class method for processing, and the subclass method processes the attributes of the subclass itself-(id) initWithName :( NSString *) name andAge :( int) age andNo :( int) no {// pass name and age to the parent class method for initialization, no in this class initialization uses the custom constructor if (self = [super initWithName: name andAge: age]) {_ no = no;} return self ;}@ endmain. m # import <Foundation/Foundation. h> # import "Person. h "# import" Student. h "int main (int argc, const char * argv []) {@ autoreleasepool {Student * p = [[Student alloc] initWithName: @" Jim "andAge: 29 andNo: 10];} return 0 ;}
After each object is created, there is a default name, age, and student ID, but each person's results are different. In this case, you need to use the custom constructor to initialize. Otherwise, the names will be the same if the override constructor is initialized (without parameters. Does not meet the program requirements.
First, create a student object, initialize the Object Pointer p (pointing to the object), first find the initWithName method in this class, and then enter the execution, upload the name and age (both inherited attributes) to the parent class method for initialization: in this way, the division of labor is clear (in fact, the same idea as c ++) And you can do your own thing, it embodies a good architectural philosophy. The advantage of doing so is that if we all initialize the child classes in a uniform way, once the name of the member variable of the parent class changes, the Code of the Child classes may fail, it needs to be modified. Once the project is large, the consequences will be unimaginable, and the division of labor is clear, you can do your own thing, let the parent class members initialize the parent class, and the Child class only needs its own, it can be retained.