"Objective-c" book Reading notes

Source: Internet
Author: User
Tags uppercase letter

* Represents a pointer with an address
The ID can be used to hold a reference pointer, such as:
void Drawshapes (ID shapes[],int count) {
ID shape = shapes[0];
}
[Shape draw] in Objective_c, the square can also represent: used to notify an object of what to do. The first item in the square brackets is the object, and the remainder is the action that needs to be performed by the object. The notification name is a Shape object that performs a draw operation.

In Objective_c, notifies an object to perform some action as a send message (also known as a "calling method"). The code [shape draw] indicates that a draw message was sent to the Shape object. [Shape draw] can be understood as "send draw message to shape."

The first uppercase class name, and the variable that points to the object does not require an uppercase letter.

A message is an action that an object can take to inform an object what to do, and in [shape draw] code, to notify the object to draw itself by sending a draw message to the Shape object. After the object accepts the message, it queries the appropriate class to find the correct code to run.

Method is code that runs in response to a message.
Method scheduling, which is a mechanism used by objective-c, is used to speculate on what methods are executed to correspond to a particular message.

Write the initialization method:
(ID) init{
if (self = [super init]) {
engine = [engine new];
Tires[0] = [Tire new];
TIRES[1] = [Tire new];
}
return (self);
}//init

The magical of the point expression
If the point expression appears to the left of the equals sign (=), the setter method for the variable name (-setrainhandling: and-setsnowhandling:) is called. If the point expression appears to the right of the object variable, the Getter method (-rainhandling and-snowhandling) of the variable name is called
If you encounter a strange error message accessing the property, and you are prompted to access the object that is not a struct type, check that the current class already contains all the required header files that you want.


--------------@interface Part

@interface Circle:nsobject
{
@private
Shapecolor FillColor;
Shaperect bounds;
}

-(void) Setfillcolor: (Shapecolor) FillColor;
-(void) SetBounds: (shaperect) bounds;

As long as you see the @ symbol in Objective-c, you can think of it as an extension of the C language.

-(void) draw; The preceding short line indicates that this is a declaration of the Objective-c method. This is a way of distinguishing between function prototypes and method declarations, and there is no antecedent in the function prototype. The short line is the return value of the method, which is enclosed within parentheses.

-(void) Setfillcolor: (Shapecolor) FillColor;
-(void) SetBounds: (shaperect) bounds;
Each of these methods has a parameter, Setfillcolor has a color parameter, and the circle class uses that color when it paints itself. SetBounds: There is a rectangular region parameter, and the circle class uses that area to determine their boundaries.

infix characters
Objective-c has a syntax technique called infix (infix notation). The name of the method and its arguments are all combined.
For example, you could call a method with a parameter like this:
[Circle Setfillcolor:kredcolor]
A method call with two parameters is as follows:
[Textthing setstringvalue:@ "Hello three" color:kbluecolor];

Note Colon
Note that the colon is a very important part of the method name. Method
-(void) scratchthecat;
differs from
-(void) Scratchthecat: (Cattype) critter;
If the method uses parameters, a colon is required, otherwise no colon is required.

The last line of code tells the compiler that we have completed the declaration of the Circle class.
@end//circle
While this is not necessary, we advocate adding comments to all @end statements to indicate the name of the class. It's a good habit.

[Email protected] section
Interface section, a common excuse for defining classes. Typically, an interface is called an API. The code that really enables the object to run is in the @implementation section.
The following is the complete circle class implementation:

@implementation Circle

-(void) Setfillcolor: (Shapecolor) C
{
FillColor = C;
}//setfillcolor

-(void) SetBounds: (shaperect) b
{
bounds = b;
}//setbounds
In @implementation Circle, FillColor and bounds are the variables that directly inherit the @interface declaration, so no additional definition is required.

@implementation Circle is a compiler directive that indicates that you will provide code for a class. After the class name appears again @implementation. There is no semicolon at the end of the line because you do not have to use a semicolon after the objective-c compiler directive.

You might think that since the method is defined in the @implementation directive alone, it cannot be accessed from outside the implementation. But this is not the case, there is no real private method in Objective-c, and you cannot identify a method that is not private, thereby preventing other code from calling it. This is a side effect of the obective-c dynamic nature.

The parameter names between the @interface and @implemention are allowed.

To set the access method for the engine property:
-(engine *) engine;
-(void) Setengine: (Engine *) newengine;
Implementation code:
-(engine*) Engine
{
return (engine);
}

-(void) Setengine: (Engine *) newengine
{
engine = Newengine;
}

Actual use:
Engine *engine = [engine new]
[Car setengine:engine];
NSLog (@ "The car's engine is%@", [car engine]);


To set the access method for the Tires property:
The tires access method is slightly more complex:
-(void) Settire: (Tire *) Tire atindex: (int) index;
-(Tire *) Tireatindex: (int) index;

Implementation code:
-(void) Settire: (Tire *) Tire atindex: (int) inex{
if (Index < 0 | | index>3) {
NSLog (@ "bad index (%d) in Settire:atindex:", index);
Exit (1);
}
Tires[index] = tire;
}

-(Tire *) Tireatindex: (int) index
{
if (Index < 0 | |, index >3) {
NSLog (@ "bad index (%d) in" Tireatindex: ", index;
Exit (1);
}
Return (Tires[index]);
}


The code for the iOS class is divided into two parts.
Part of the interface is used to show the construction of the class. The interface contains all the information that is required to use the class. After the compiler has compiled the @interface part, you can use the class's objects, call the class methods, compound the objects into other classes, and create subclasses.
Another component of the source code is implementation. The @implementation section tells the Objectiveive-c compiler how to make the class work. This part of the code implements the method that the interface declares.


@interface is placed in the. h header file, @implementation is placed in the. m source file.
Cut the @interface portion of the tire class into the carparts-split.m file and paste it into Tire.h, and the file should resemble the following

#import <Cocoa/Cocoa.h>

@interface Tire:nsobject
@end

Next, cut the @implementation part of the Tire class from carparts-split.m and paste it into TIRE.M, and you need to add the statement #import "Tire.h" to the first line of the file. The file should resemble the following.

#import "Tire"
@implementation Tire
-(NSString *) description
{
Return (@ "I am a tire. Ilast a while);
}
@end;
The first import statement in the file does not import the header file Cocoa.h or Foundation.h as before, but instead imports the header file of the class. This is a standardized process. When the program compiles, if you run into an injection "cannot find interface declaration for Tire" (Unable to find the interface definition of the Tire Class)


Reduce dependencies:
Objective-c introduced the keyword @class to tell the compiler: "This is a class, so I will only refer to it by pointers"
@class is used when moving the car class to a file that belongs to itself. In Xcode, use and migrate the same methods as the tire class and the engine class to create Car.h and car.m to copy the @interface portion of the car and paste it into Car.h as follows:

#import <Cocoa/Cocoa.h>

@interface Car:nsobject
-(void) Setengine: (engine*) Newengine;
-(engine *) engine;
-(void) Settire: (Tire *) Tire atindex: (int) index;
-(Tire *) Tireatindex: (int) index;
-(void) print;
@end//car
If we use this header file now, we will get an error message from the compiler telling us that we don't understand what trie and engine are. This error message is likely to look like this: error:expected a Type "Tire", compiler this is saying, "I can't understand this."
There are two ways to solve this error problem. The first is to import Tire.h and engine.h with @import statements. This allows the compiler to get a lot of information about these two classes.
There is also a better way. If you look closely at the excuse of car class, you will find that it simply refers to tire and engine by pointers. This is the work that @class can do. Here is the content of the Car.h file that joins the @class code.

#import <Cocoa/Cocoa.h>

@class Tire;
@class Engine;
@interfaceCar: NSObject
-(void) Setengine: (Engine *) newengine;
-(engine *) engine;
-(void) Settire: (Tire *) Tireatindex: (int) index;
-(tire*) Tireatindex: (int) index;
-(void) print;
@end//car
This is enough to tell the compiler to handle all the information that is needed for the @interface part of the car class.
Description: @class difference Ungjainle a front and back reference. This is telling the compiler: "Trust me." You will naturally know what this class is, but now you know it is enough.
If there is a circular dependency relationship. @class is also useful. That Class A uses Class B, and Class B also uses Class A. If the view uses the #inport statement to refer to these two classes to each other, a compilation error occurs. However, if you use @class B in the A.h file, @class A is used in B.h, then these two classes can be referenced to one another.

The compiler needs to know all the information about the superclass before it can successfully compile the @interface section for its subclasses.


Foundationkit Introduction
Some useful data types
typedef struct _nsrange{
Unsignedintlocation;
unsigned intlength;
}nsrange;
This struct is used to denote the scope of a related thing, usually the range of characters in a string or the range of elements in an array. The Location field is held at the start of the range, and the length field is the number of elements contained within that range. In the string "Objective-c is a cool language", the word cool can be represented by the range of location for 17,length 4. Location can also use the Nsnotfound value to indicate that there is no scope, such as the variable is not initialized.
There are three ways to create Nsrange,
First, assign a value directly to the field:
Nsrangerange;
Range.location = 17;
Range.length = 4;
The second application of C-language aggregation structure assignment mechanism
Nsrange range = {17,4};
The third Way is cocoa provides a shortcut function Nsmakerange ();
Nsrange range = Nsmakerange (17,4);
The advantage of using Nsmakerange () is that you can use it anywhere you can use a function, such as passing it as a parameter in a call to a method.
[Anobjectiveflarbulatewithrange:nsmakerange (13,15)];

Geometry data type
You often see the types of data used to work with geometry, with their names with CG prefixes, such as cgpoint and cgsize. These types are provided by the Coregraphics framework for 2D rendering. Coregraphics is written in C language. Therefore, you can use the C language data type in your code. Cgpoint represents a coordinate in the Cartesian plane.
Structcgpoint
{
float x;
Float y;
}
Cgsize is used to store length and width;
Structcgsize
{
float width;
Floatheight;
}

String:

About size
Another useful method in NSString (instance method) is length, which returns the number of characters in a string
-(nsstring) length;
Can use it this way;
Nsuintegerlength=[heightlength];
You can also use it in an expression, as shown below.
if ([height length] > 35) {
NSLog (@ "Wow,you ' re really tall!");
}
Description: The length method of NSString can handle strings of various languages with precision and accuracy, such as strings containing Russian, Chinese, or Japanese characters, and strings using the Unicode international character standard.

string comparison
Isequaltostring: Can be used to compare the receiver (receiver, the object receiving the message) and the string passed as a parameter. Isequaltostring: Returns a bool value (yes or no) to indicate whether the contents of the two string are the same.
To compare two strings, you can use the Compare: method, which is declared as follows.
-(Nscomparisonresult) Compare: (NSString *) astring;
Compare: Compares the received object and the string at the bottom of the bed, and returns a Nscomparisonresult (that is, an enum enumeration) to display the results of the comparison.
enum{
Nsorderascending=-1,
Nsordersame,
Nsorderdescending
}
Typedefnsintegernscomparisonresult;

Description: Correctly compares strings,
When comparing two strings for equality, you should use isequaltostring, rather than just comparing the Zhi pointer values of a string, for example:
if ([thing1 isequaltostring:thing2]) {
NSLog (@ "TheString is the same!");
}//comparing the contents of a two string

differs from
if (thing1==thing2) {
NSLog (@ "They is the same objective!");
}//determines the number of pointers to two strings, not the objects they refer to.

Therefore, if you want to check whether two objects (THING1 and thing2) are the same thing, you should use operator = =. If you want to see if they are equal (that is, if the two strings are the same), then use isequaltostring.

Compare: A case-sensitive comparison is made. The comparison of @ "Bork" and @ "Bork" does not return nsordedsame. If compare: The returned result is nsorderedascending, then the value on the left is less than the value on the right, that is, the target of the comparison is sorted in the alphabet more forward than the string passed in. For example, [@ "Aardvark" Compare: @ "zygote"] will return nsorderedascending.

Checks whether a string begins with another string and determines whether the string ends with another string.
-(BOOL) Hasprefix: (NSString *) astring;
-(Bool) Hassuffix: (NSString *) astring;

Cases:
nsstring*filename=@ "Draft-chapter.pages";
if ([FileName Hasprefix: @ "Draft"]) {
Thisisadraft
}
if ([Filenamehassuffix: @ ". mov"]) {
Thisisamovie
}
If you want to know if a string contains other strings, use rangeofstring:.
-(Nsrange) rangeofstring: (NSString *) astring;
When you send rangeofstring: to a NSString object, the arguments that are passed are the characters you want to find. It will return a nsrange struct. Tells you where to match the string and the number of characters that can match.
Cases:
nsrangerange= [filenamerangeofstring:@ "chapter"];
The returned range.location is 6,range.length to 7. If the passed parameter is not found in the receive string, then Range.location equals Nsnotfound.

The Nsarray class has two restrictions. First, it can store only objectiveive-c objects, not the original C-language underlying data types, such as random pointers in Int,float,enum,struct and Nsarray. Also, you cannot store nil (0 or null values of objects) in Nsarray. There are a number of ways to avoid these limitations and you will see them right away.
You can arraywithobjective by using the class method: Create a new nsarray. Sends a comma-delimited list of objects, adding nil to the end of the list (by the way, that's one reason you can't store nil in the array).
Nsarray creates an immutable group. Once an array containing a specific number of objects has been created, it is fixed and cannot be added or deleted. Of course, the objects contained in the array can be changed.
In order to compensate for the Nsarray class, there is nsmutablearray this variable array class.

Initialize the object:
We should call the Alloc and Init methods in such a nested way as below
Car *car = [[Car alloc] init];
And not like this.
Car *car = [Car alloc]; [Car init];
This nested invocation technique is important because the initialization method returns an object that may be different from the assigned object, although this is a strange situation, but it does happen.

The magic of point expressions, if you encounter a strange error message when accessing a property, you are prompted to access an object other than the struct type, check that the current class already contains the required header file.

@class Tire;
@class Engine;
@interface Car:nsobject
{
Nsstring*name;
Nsmutablearray*tires;
Engine*engine;
}

-(void) SetName: (NSString *) newName;
-(NSString *) name;
-(void) Setengine: (Engine *) newengine;
-(void) Settire: (tire*) Tireatindex: (int) index;
-(Tire *) Tireatindex: (int) index;
-(void) print;
@end//car

Memory Management Release
If the object is produced through the alloc, copy, new method, it needs to be released through release. If the object is produced in another way, it does not need to be released manually, such as Numberwithunsignedint, because the object it returns may be a retention counter with a value of 1 and has been set to automatically release. The NSNumber object that we created is also cleaned up when the currently active automatic release pool is destroyed.

page = 15th Chapter 245

"Objective-c" book Reading notes

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.