Excerpt from the basic notes on OC

Source: Internet
Author: User

An excerpt from the basic notes of OC:

1. Basic usage of Classes

#import <Foundation/Foundation.h>
In general, include, used to include header files, but even if there is no ifndef defined endif in the header file, it is still possible to kick the header file except for the duplicate included
[Email protected] section----
The Declaration and implementation in OC are separate, and two must have one.
@interface Fraction:nsobject {//@interface class Name: Parent class name
Declare a member variable here, called a field in OC, which describes the properties of the object of the class
Member variables need to be defined in the. h file only if the member variables need to be provided externally, or when they need to be inherited, and in other cases only in. m files, declare global variables to
int _numerator; Use member variables within a class to use attributes outside of the class
int _denominator;
}
@property (nonatomic, assign) int numerator, denominator;
-(void) Setnumerator: (int) n; Declaring methods
-(void) Setnumerator: (int) n anddenominator: (int) D;
-(fraction *) init; or use-(ID) init; In OC, as long as it starts with INIT, it is a constructor that can take parameters
@end

[Email protected] section----method Implementation---instance method (beginning with a-number)----class method (beginning with the + sign)
@implementation Fraction//@implementation class name
@synthesize numerator = _numerator, denominator = _denominator;
-(void) Setnumerator: (int) n anddenominator: (int) D;
{
_numerator = n;
_denominator = D;
}
-(fraction *) init
{
if (self = [super init]) {
Super is a pointer to the parent class, and super has the same value as self, and fraction has not only its own member variables, but also the contents of the parent class, so initialize the contents of the parent class before initializing its own content.
_numerator = _denominator = 0;
}
return self; Self is the address of the current object and is equivalent to a member variable
}

@end

----Program section----main function part

int main (int argc, const char * argv[])
{

@autoreleasepool {//Reserved space in memory for the auto-free pool

Fraction *myfraction = [[Fraction alloc] init]; Declares an object of a class, allocates memory space, and initializes
OC does not allow objects of the class to be created in the stack, the objects of their own classes can only be created in the heap
[Fraction alloc] This expression creates a fraction object in the heap space, the value of the expression is the address of the object, Myfraction is just the pointer to the object
or use fraction *myfraction = [fraction new];
[Myfraction setnumerator:1]; Sends the message to the object, calls the Setnumerator method, and passes a parameter of 1.
Call the method Setnumerator of the object that myfraction points to,
The address of the object (not the pointer) of the method that called the object, (the address is constant, the pointer is a variable)
Also known as sending Setnumerator messages to objects

OC is fully compatible with C; OC has its own dedicated string and is also compatible with the C string
NSLog (@ "The value of Myfraction is:"); Display, @ Represents a NSString string object and is not added as a normal string
}
return 0;
}

2. Immutable strings
The OC string is an object whose type is the NSString class.
OC therefore uses its own proprietary string, because this string is an object, there are many methods, more convenient than foreign functions such as strlen, and more object-oriented.
NSString * str = @ "Hello world!";
@ "Hello world!" This expression means that in the read-only data segment, a NSString object is created, the content is Hello world!, the value of the expression is the address of the object, and only the string can create an object like this
The NSString object is immutable.
The Nsmutablestring object is mutable.

NSString * str2 = [[NSString alloc] initwithstring:str];

NSString * STR3 = [[NSString alloc] initwithutf8string: "HEllo world!"];
Create OC string with C string, complete C string into OC string
char * cString = [@ "Objective-c String" utf8string]; Converting an OC string to a C string

NSString * STR4 = [[NSString alloc] initwithformat:@ "Hello%c%d%f", ' A ', 3, 3.14];
Based on the format character, stitching creates a string, the most powerful

There are also class methods [NSString STRINGWITHSTRING:STR];
[NSString stringwithutf8string: "Hello"];
[NSString stringwithformat:@ "Hello%d", 5];

Characteratindex
Length//No tail 0

Convert case:
Uppercasestring//ALL CAPS
lowercasestring//Full lowercase
Capitalizedstring//Capitalize the first letter of the word
Compare Size:
Isequaltostring
Compare
Hasprefix://Whether the prefix is included
Hassuffix://Whether the suffix is included

Find:
Rangeofstring finds the range of substrings in a string, range.location range.length

Extract substring:
Substringtoindex
Substringfromindex
Substringwithrange

The object of the struct can be stored in the stack, and the object of the class cannot be stored in the stack.

3. Variable string
Nsmutablestring:nsstring
NSString's method nsmutablestring can also be used
You can pass nsstring when you pass a parameter * or you can pass Nsmutablestring *

SetString to set or replace the current string contents

Increase:
Added: appendString AppendFormat
Insert: Insertstring:atindex:
By deleting:
Deletecharactersinrange
The function that generates range Nsmakerange (2, 4);
Change:
Replacecharactersinrange:withstring:
Check:
Rangeofstring

4. Categories
Only OC has category (CategoryName)
Class is the upgrade patch for classes that can be inherited
Categories cannot be used to add member variables, only methods (including class methods and member methods) can be added

5. Non-variable groups
The elements of an array are arbitrary objects, not just strings, but only the addresses of the objects in the array. Equivalent to an array of pointers.
Unlike arrays in C, an element can be a different type of object, structurally speaking, it is a linked list.
Initwithobjects

All objects are printed using%@, and this class has a description method
-(NSString *) description; The description method can only write this way, printing the method's return value, the Chinese support is not good

Direct traversal:
NSLog (@ "%@", arrayname);
Enumeration method Traversal:
Creates an enumerator (Nsenumerator *) enumerator = [Array Objectenumerator] with the current array, and then invokes the Nextobject method of the enumerator, returning the address of each element in the array.
Fast Enumeration Method:
for (id obj in arrayname) {}
The for that is specifically used to enumerate the arrays, and the usual for is not one. Each loop gets the address of an array element.
Loop traversal:
Objectatindex://Returns the address of an element in an array
Indexofobject://Subscript of an element
Count//Number of elements

[Array Containsobject:]//array contains an element

Componentsjoinedbystring://Combine elements in an array
Componentsseparatedbystring://Split string
Componentsseparatedbycharactersinset:[nscharacterset charactersetwithcharactersinstring:]//Use character to split string

6. Variable array
Initialization
Initwitharray
[Arrayname Objectsatindexes]
SetArray

Enumeration method is not allowed to modify the elements and the number and order, the fast enumeration method is not possible, but in reverse enumeration when the Reverseobjectenumerator can be modified

Increase:
AddObject
Insertobject:atindex:

Delete:
Removeobjectatindex
Removeobject

Exchange Replace

Sort:
Sortusingselector: @selector (Isbigthan:)//selector is called a selector, a function pointer equivalent to a member method

7.SEL
SEL is a type, a variable declared with the SEL, containing a message, such as: sel s = @selector (methodName); There are parameters to write: That is, the full method name
@selector actually returns the name ID; The function is to make the method assignable, so it is possible to pass a parameter, which can be used as a function parameter
The compiler assigns each method a number (0, 1, ...), called the name ID, in different classes, as long as the name of the method is the same, the name ID is the same, but the entry address of each method is different.
[ObjectName performselector:s Withobject:]//Restore method, and call, with 1 parameters, add 1 withobject, up to a maximum of 2
Repondestoselector: @selector ()//object can respond to selector specified method

8.Class
Class is also a type, which is a variable of class, such as: Class CLS = [ClassName class]; You can then use CLS instead of classname
The function is to enable the class to be assigned a value, so it can be used for iskindofclass: [ClassName class]//Whether it is a ClassName class or its subclasses
Issubclassofclass:[classname class]

9. Dictionaries
Nsmutabledictionary:nsdictionary
Initwithobjectsandkeys:
The members in the dictionary are called key-value pairs, and @ "one" and @ "1" make up a key-value pair, @ "A" is called the value (value), @ "1" is called the Key (key);
Keys and values are arbitrary objects, however, keys often use a string, the dictionary is only the key and the value of the address, the value can be repeated, but the key cannot be repeated, for the same key set value, will replace the original value
There is no order for the key-value pairs in the dictionary, not the first second, and the arrays are not the same, and the structure is also a linked list
Objectforkey//can quickly find a value by key (value)
Number of Count//key-value pairs
There are two kinds of enumeration traversal, through key enumeration traversal (Keyenumerator), by value enumeration traversal [Objectenumerator], Fast enumeration method, the key is traversed,
Setobject:forkey:
Removeobjectforkey

10.setter, Getter, @property
In setter, getter, you can use the. operator, if it is an assignment, is using the Set method, and if you are using a private variable, use the Get method
@property (readonly)//indicates that only the Get method is created, no set method is created, no write only
(atomic)//atomic operation, with this parameter, before the end of this thread run, no other thread is allowed to use the resources I have used, under normal circumstances, the thread is able to use the same resource, and multiple threads can alternate between running
(nonatomic)//Do not need atomic operation, the default is atomic operation, so sometimes add this parameter
@property (getter = othername) int name; Modify the default getter name name is Othername, use the same time can use these two names
@property (setter = Setother:)//setter must be followed by a colon;
(assign) and (ReadWrite) are default properties, do not need to write, sometimes write assign, indicating that no other properties are needed, and not forgetting to write other properties
such as: @property NSString * name; Then there will be errors, written @property (assign) NSString * name; There's no mistake.
Between multiple attributes, separated by commas
(copy) (retain)//When declaring an object, add release to Dealloc.
NSString use Copy, the other objects are retain, and the basic data types are the default assign

11. Inheritance
Polymorphic: Methods of the same name, do different things, have overloads, overrides, virtual functions
Encapsulation: A complex function that encapsulates a relatively simple code, such as a function, macro, @property, struct, class
Private: Can not be a quilt class inheritance, can not be accessed by external functions, but when inheriting, the subclass also gave private space,
Protected: can inherit the quilt class, cannot be accessed by external function
Public: can continue to quilt class, can be accessed by external functions
There are three ways to inherit from C + +, but the permissions for variables are completely different. Private inheritance, inherited members, all become privately owned; Protected inheritance, inherited members, all become protected; Public inheritance, inherited from the member, what is the original permissions, or what permissions.
Only the public inheritance in OC, after the subclass inherits, a number of variables, is called derivation, the members of the subclass are divided into two parts: inheritance and derivation.
Inheritance is the complete inheritance of the parent class all, using the method inherited from the parent class, you can access the parent class's private members, although there is no private member of the parent class, but it is allocated space

NSString, Nsarray, nsdictionary these three classes cannot be inherited by programmers themselves

Virtual functions: All member methods in OC are virtual functions,
1) The pointer of the parent class can point to the object of the child class
2) when calling a method, do not look at the pointer only the object
Different things are triggered by the same event, resulting in different responses

12.
Stacks: (places where functions, structures, variables, etc. are stored)
Heap:
Data segment:
Read-only data segment:
Code snippet: (Tell the CPU what to do, and then start doing it in the stack) (the entry address of the structure such as function is in the code snippet, the entity is stored in the stack)
Press Stack

13. Memory Management
is the creation and release of heap space problems, C language in the release of the heap, there is insufficient, so OC has its own memory management
Assign a heap to an object, just set the heap to private, release the object, set the heap space to public, but the contents of the heap are still there, not lost, unless the heap space is overwritten (re-assigned).
C language does not release will occur memory leaks, released two times, will be repeated release, free (p), the release of the heap space P points, C also has a similar to OC counters, called PV operations (plus and minus operations), but need to write their own counters, and release functions
Alloc, the counter is automatically set to 1, retain counter plus 1, release minus 1, retaincount view reference count
Memory Management Golden rule:
1. (generally accepted) when using Alloc, retain, copy, mutablecopy, new "Create" an object, or add a pointer, you must use release or autorelease for "free".
2. (non-recognized) each pointer to do its own memory management, each class to do their own memory management, each person.

Objects placed in the read-only data segment, the counter is set to a negative number ( -1), retain met negative, nothing will do, do not modify the counter, because the read-only data segment can not be modified
-(void) dealloc; Destructors, no arguments, no overloads
The set method of the constant string, if (name! = newName) {[name release]; name = [NewName retain];}, followed by the addition of [name release] in Dealloc; [Super Dealloc];

Autorelease, the object will be released in the nearest auto-release pool using Autorelease objects, and when the pool is released. In principle, do not use autorelease unless it is a last resort. In the class method, the autorelease is generally used; It is best to use the Get object, return [[name retain] autorelease];
An automatic release pool is created and released for each trigger cycle under the iOS system
Another is arc (automatic management of memory)

14. Agreement
A protocol is a mechanism to complete communication between two classes, passing information between objects of two classes.
The sender holds the agreement and the receiving Party complies with the agreement.
@protocol <protocolName> ID <protocolName> delegatename;
The @required//compliance class must implement the method, the default property
@optional//Optional
The method declared in the protocol, the class conforming to the protocol can not write the declaration, the direct write implementation
If the two objects are mutual proxies, that is, each other as a reference, if all are counted, a deadlock will occur; So when two objects are proxies to each other, if a->p = [B retain], (A to B strong reference), then B->p = A, (B to a weak reference) do not count.
One-way agreement, if the protocol is not placed in a single file, the protocol is placed in the sender's protocol, because the sender is likely to be a member of the receiver, if the protocol is placed in the receiver, the header file contains a ring.
Conformstoprotocol: @protocol ()

15. Documents
1) Operations on the file itself (Nsfilemanager File Manager)
[Nsfilemanager Defaultmanager]//Declare a Nsfilemanager object
[Contentsofdirectoryatpath:error: &error]//shallow traversal, view the contents of the current directory, the return value is an array; If there is no error, error returns nil, otherwise a Nserror object is created in the heap and the address of the object is assigned to error; Address, just to modify the value stored in the address
[Subpathsofdirectoryatpath:error: &error]//deep traversal, not only to traverse the current directory of files, but also to traverse the contents of subdirectories
CreateDirectoryAtPath:withIntermediateDirectories:NO Attributes:nil Error: &error];
Create a directory; The second parameter, if incoming yes, will automatically create an intermediate directory (MKDIR-P), if the incoming no, as long as the intermediate directory does not exist, the error; The third parameter, which sets the properties of the directory, passes in nil, as a general (default default) attribute;
CreateFileAtPath:contents:attributes://Create File
String comes with a datausingencoding: A string is stored in NSData, Data.bytes reads the contents of data
Removeitematpath:error:&error//deleting files or directories
CopyItemAtPath:toPath:error://Copy, file name must be written in full
Attributesofitematpath:error://Get file attributes, put in dictionary
Fileexistsatpath://Determine if the file exists
Fileexistsatpath:isdirectory://Determine if the file exists and whether it is a folder

2) operation on the contents of the file (nsfilehandle file handle)
From file to memory is read, from memory to file is write
The file pointer (pointer) files pointer to the file descriptor (number) file descriptor of the files handle (object) handle, which is written in the file handle to the file
[Nsfilehandle Filehandleforreadingatpath:]//Open file handle in read-only mode
Readdatatoendoffile
Readdataoflength//Read two times, do not start from the beginning to read, but each read and then read the last location read down
String method: Initwithdata:encoding//Data to String datausingencoding://String to data
Filehandleforwritingatpath://Open the file in a write-only manner, if the file does not exist, then create the file, in C "W" will empty the original file, OC is an overlay of one
WriteData://write the first time from scratch, and then write it down the second time
Seektoendoffile//Placing the read-write pointer at the end of the file
Seektofileoffset://Place the read-write pointer to the file specified position, 0 is the first file
Truncatefileatoffset://Empty (truncate) a file, leaving only the first n bytes
Filehandleforupdatingatpath://Read/write operation

16.NSDate
NSDate * date = [NSDate date]; Create a Date object with the current time
[NSDate Datewithtimeintervalsincenow:seconds]//Use a time interval (seconds) to indicate a past or future period
[[NSDate Date] timeintervalsincedate:date]//Compare date with date saved in date
[Nsthread sleepuntildate: [NSDate Datewithtimeintervalsincenow:]]; Let the application hibernate for a while

NSDateFormatter//Converts a date to a fully formatted string
Dateformatter.dateformat = @ "Mm/dd/yy HH:mm:ss";
[Dateformatter stringfromdate: [NSDate Date]];

[Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector () Userinfo:nil Repeats:yes]
This timer is triggered after 1 seconds and is continuously cycled until the timer is disabled ([timer invalidate])

Excerpt from the basic notes on OC

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.