Import directive (copies the contents of the file at precompile time to where the directive was written)

import <Foundation/Foundation.h>

Foundation framework

NSLog(@”Hello, World!”) );


NSString * STR = @"jack"; String placeholder: %@

The data type

Data types supported by the C language

Basic data types

int double float char

Structural type

Enumeration of array structures

Pointer types

int *p1

Empty type


Typedef custom types

BOOl type YES/NO

True/false Boolean type

Class class

A universal pointer of type id

Nil is similar to NULL

SEL method selector

Block of code


The definition of a class

@inteface class name: NSObject {} @inteface Person: NSObject {NSString *_name; int _age; float _height; } - (void)run; - (void)run: (parameter type) Parameter name; - (void)run: (parameter type 1) parameter name 1: (parameter type 2) parameter name 2; - (void)eat : (NSString *)foodName; - (void)sum : (int)num1 : (int)num2; @end implementation: @implementation Person - (void)run {NSLog(@" This is a method "); } - (void)eat: (NSString *) FoodName {NSLog(@" This is an argument to a method %@", FoodName); } - (int)sum : (int)num1 : (int)num2 { int sum = num1 + num2; NSLog(@"num1 and num2 are %d", sum); return sum; } @end


Person *p1 = [Person new];

Calling an instance method

[p1 run]; [p1 eat: @" braised pork ribs "]; [p1 eat: 1: 2];

Method to access properties

The difference between NULL and nil

NULL is generally used when a pointer does not point to any space in memory and nil is generally used when a pointer to a class does not point to any object

Class to encapsulate



Objects and relationships between objects (composition/dependency/association/inheritance)

The static keyword

The static keyword in C language

A. to modify local variables B. to modify global variables C. to modify functions

The static keyword in OC

A. static modifies a property and a method B. static modifies a local variable in a method

If the method’s return value is an object of the current class, then the method’s return value is written to InstanceType

The self keyword

Gets the address of a class in a code snippet

A. Debug the value of the Isa pointer of the Viewer B. View the value of self in the class method C. View the value of self in the class method Calling the object method class on the object returns the address in the code of the class to which the object belongs. Calling the class method of the class [Person Class]

Class inheritance

Syntax (inherits all properties and methods, including static methods and static properties and class methods): @inteface Chinese: Person {} @end @implementation Chinese {} @end

The super keyword

Access modifier (default is protected)

@Inteface Chinese: NSObject {@private NSString *_name = "Felix"; @private NSString *_name = "Felix"; } @End@Implementation Chinese {} @End@Protected (Accessible only in the object methods of this class and subclasses, not through objects) @Package (Accessible only in the current framework, Understand) @publick(accessible from anywhere) Modifiers can only modify properties, not methods;

Private property

I'm going to put the property inside implementation

Private methods

Write only the implementation, not the declaration

Subclass mode overriding

Subclasses can be overridden at the time of implementation

Description method (each class has a =description method that prints the address of the object, which you can override to suit your needs)

Sel object

Dot syntax (that is, calling the setter or getter method of the calling object)


Automatically generate the declaration of setter and getter methods (define it or write it yourself); @inteface Person : NSObject { NSString *_name; int _age; } - (void) setName: (NSString *) name; - (NSString *) name; @property int age; - (void) setName: (NSString *) Name; // - (NSString *) name; @end


Automatically generate the getter/setter implementation syntax @synthesize @property name; Example: @inteface Person: NSObject {NSString *_name; int _age; } @property int age; @end @implementation Person @synthesize @end

@ property enhancement

@inteface Person : NSObject @property NSString *name; @end 1) Generate a private property of type NSString and attribute name _name 2) Generate getter/setter declaration 3) Generate getter/setter implementation

Static and dynamic typing

Static type: The object to which a pointer points is an object of the class; Dynamic type: The object to which a pointer points is not an object of the class;

Id pointer –> universal pointer type, can point to any OC object

id id1 = [Person new];

InstanceType means that the return value of the method is the object of the current class

Syntax + (InstanceType)person {return [self person]; }

Dynamic type detection

IntanceresOnseSelector determines whether a method exists in a class

Resonsei Selector determines whether there is a method in an object

Person *p1 = [Person new];
BOOL res = [p1 resonseToSelector:@selector(sayHi)];

The isKindofClass method (object method) determines whether the specified object is an object of the specified class or a subclass object

[s1 isKindOfClass: [Person class]]

The isMemberOfClass method (object method) determines whether the specified object is an object of the specified class, not including subclasses

[s1 isMemberOfClass: [Person class]]

The isSubClassOfClass method (given by the class norm) determines whether the specified object is an object of a subclass of the specified class

A constructor

Override the specification of the init method

2) Init may fail to initialize the object. If it fails, the return value will be nil. 3) Whether the parent class was successfully initialized, if it was successfully initialized, the return value will be nil. 4) Finally, return the value of self

@implementation Person - (instancetype)init { self = [super init]; if (self ! = nil) { } return slef; } @end

The init method with arguments

1) Init specification 2) Must start with InitWith and 3) The return value must be InstanceType

@inteface Person - (InstanceType)initWithName:(NSString *) Name andAge:(int) Age; @end implementation Person - (InstanceType)initWithName:(NSString *) Name andAge:(int) Age {self = [super init]; if (self ! = nil) { = name; self.age = age; } return slef; } @end call Person *felix = [[Person alloc] initWithName: @" flower "andAge: 18]

Memory management

Stack area: local variables, when the scope of local variables is executed, the local variables will be system immediately collected heap area: OC object, C function application of dynamic space BSS: an uninitialized global variables, static variables, once after initialization can be recycled, and transfer to the data in the data section: Global variables, static variables, that have been initialized, are not retrieved until the end of the program: code, at the end of the program the system will automatically retrieve the data stored in the code segment

Reference counter

1) Each object has a property: retainCount, called a reference counter, of type unsigned long, which occupies 8 bytes; The reference counter is used to keep track of how many people are currently using the object

Classification of memory management

Arc: Manual Reference Counting and memory management. Arc: Automatic Reference Counting and memory management. Arc: Automatic Reference Counting and memory management

Overriding the dealloc specification

It is necessary to call the parent dealloc method, and the method calling the parent dealloc must be placed at the end of the dealloc method.

@ property parameters

The four groups of parameters to @Property (parameters can be written in any order, but usually in the following order). The two parameters associated with multi-threading are atomic(multi-threading safe lock: safe, inefficient) nonatomic(without multi-threading safe lock: unsafe, efficient). Assign: Default value, the generated setter method retains: The generated setter method is standard MRC memory management. If it is the same object, release it and retain it. If it is the same object, use retain; otherwise use assign. To manually write override dealloc method c. ReadOnly: read-only, generates getter, does not generate setter readwrite: default, generates getter and setter d. Getter, setter @property(nonatomic, assign, getter = methodName) age; @property(nonatomic, assign, setter = methodName:) age; E. Stong, weak represents whether the pointer is strongly typed or weak-typed (strongly typed by default).

# Automatic release pool

@autoreleasePool {Person *p1 = [[Person alloc] init] autorelease]; }


Note: 1) Only methods can be written in the classification, not attributes; 2) If @Property is used in the classification, only declarations will be generated automatically, not implementations, nor private properties will be generated automatically; 4) When there are methods of the same name in the class, the method of the class will be called first, even if the class header file is not introduced. If multiple categories have the same method, the last compiled category is called first.


1) extension is a special class 2) extension has no name 3) it has declaration, no implementation, and shares the same implementation with this class 4) it can only add methods to the class, any member of the extension can write 5) it can write @property, This will only generate getter setter declarations if you write @property in the extension, which will automatically generate private properties, and also automatically generate getter and setter declarations and implementation syntax: @inteface This class name () - (void)run; - (void)sleep; A private @Property extension for a class does not own a file. This extension is written directly to the class implementation file.

OC adds some new data types on top of C

BOOL Boolean class nil SEL id(universal pointer) block

Block variables

Declarations: You must specify whether or not the code stored in the block variable has an argument and whether or not it has a return value. Examples: return value type (^block variable name)(parameter list); void (^myBlock1)(); Int (^myBlock2)(int num1, int num2); int (^myBlock2)(int num1, int num2); Initialization: code snippet writing format: ^ return value list (parameter list) {code snippet; } ^void () { NSLog(@"its a"); NSLog(@"its b"); } myBlock1 = ^void () { NSLog(@"its a"); NSLog(@"its b"); } execute: myBlock1();

Use typedef to simplify complex block definitions

typedef void (^NewType)();
NewType block1;
NewType block2;

typedef int (^NewType)(int num1, int num2);

Block accesses external variables

2) You can change the value of a global variable inside the block, but you cannot change the value of a local variable outside the block. 3) If you want to change the value of a local variable outside the block, you can change the value of a global variable. __block int num = 300; __block int num = 300;

Protocol (Declare a bunch of methods, and then the class follows them)

Syntax: @inteface Person: NSObject < protocol 1, protocol 2 >

@Required (default), @Optional (not implemented, no error, required will send a warning ⚠️, but @Optional will not)

Inheritance between protocols

Syntax: @protocol protocol name < parent protocol name >@end

The agreement

1) NSObject <StudentProtocol bb0 * Pointer Name = [Student New]; id <StudentProtocol> id = [Student new]; 2) declare a pointer to an object that must adhere to multiple protocols NSObject < studentProtocol, SBPtotocol> *stu; Student <StudentProtocol> *stu;

Foundation framework

Commonly used string methods

A. String with format string concatenation [NSString String with format: B. LEN = STR. LEN = STR. LEN = STR. c. characterAtIndex Unichar ch = [str characterAtIndex: 2]; D. Range range = [STR range of string]; d. Range range = [STR range of string]; NSRange is a structure variable of type NSRange typedef struct _nsRange {nSUInteger location; NSUInteger length represents the index of the substring (none is the maximum value of an unsigned long); NSRange represents the length of the substring creation matched in the main creation (if not 0)} nsRange; F. SubstringFromindex character truncation [Str SubstringFromindex: 3]; // SubstringToIndex (1); // SubstringToIndex (2); // SubstringWihRange: nSmakeRange (2, 3); // SubstringWihRange: nSmakeRange (2, 3); / / from the specified position began to intercept, capture specified number g. stringByReplacingOccurrencesOfString string replacement (equivalent to the replace method) nsstrings * email = @ ""; / / replace the "#" email = [email stringByReplacingOccurrencesOfString: @ "#" @ "@"); H. NSString * STR = @"1"; int num = STR. int num = str.intValue; NSInteger num = str.integerValue; double num = str.doubleValue; float num = str.floatValue; long long num = str.longLongValue; bool num = str.boolValue; I. stringByTrimmingCharactersInSet removes white Spaces at the before and after the string [STR stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; J. UppercaseString [STR uppercaseString]; K. LowerCaseString to lowercase [STR lowerCaseString];

The method to create the NSRange variable

1. NSRange range;
    range.location = 3;
    range.length = 4;
2. NSRange range = { 3, 7 };
3. NSRange range = { .location = 3, .length = 7 };
4. NSRange range = NSMakeRange(3, 7);


NSMutableString *str = [NSMutableString string]; [str appendString:@"jack"]; [str appendString:@"rose"]; // Append [STR appendFormat:@" I'm %ds this year ", age]; // Append as a concatenation


A. can only store any OC object B. has a fixed length. Once the array of NSArray is created, the length of the element is fixed. NSArray *arr = [NSArray arrayWithobeJCTS: [NSArray *arr = [NSArray arrayWithobeJCTS: @"rose", @"jack", @"lilei", @"hanmeimei", nil]; Shorthand: NSArray * arr = @ [@ "rose" @ "jack", @ "lilei," @ "hanmeimei,"]

NSArray common properties and methods;

NSArray *arr = @[@"jack", @"rose", @"lilei"]; NSInteger Count = Arr. Count; Arr ObjectAtIndex: 3; Arr ObjectAtIndex: 3; [Arr containsObject: @"lili"]; [Arr containsObject: @"lili"]; 4. Get the first and last element arr.firstObject; arr.lastObject; NSUInteger index = [Arr IndexOfObject: @"rose"];

The for-in loop iterates through the element syntax

for(NSString *str in arr) {
    NSLog(@"%@", str);

Use block traversal enumerateObjectsUsingBlock

Array to NSString(JS join method)

NSArray *arr = @[@"jack", @"rose", @"jim"];
NSString *str = [arr componentsJoinedByString: @"-"];

Turn nsstrings array

NsString = @" Liuzhou City, Central District, Diwang Wealth Center "; NSArray *arr = [str componentsSeparatedByString: @","];

NSMutableArray(support for dynamic new deletion function)

1. NSMutableArray *arr4 = [NSMutableArray New]; 2. NSMutableArray *arr4 = [[NSMutableArray alloc] init]; 3. NSMutableArray *arr4 = [NSMutableArray array]; 4.NSMutableArray *arr4 = [NSmutableArray arrayWithObjects: @"jack", @"rose", @"lili", nul]; NSMutableArray *arr4 = [NSMutableArray New]; [arr4 addObject: @"jack"]; 2. New array: NSObject arr = @ [@ "jack" @ "rose", @ "Lucy," @ "Tom"); NSMutableArray *arr = [NSMutableArray new]; [arr addObjectFromArray: arr]; 3. Inserts the element at the index; NSMutableArray *arr = [NSmutableArray arrayWithObjects: @"jack", @"rose", @"lili", nul]; [arr insertObject: @"lilei" atIndex: 1]; [arr removeObjectAtIndex: 1]; 5. Removes all specified elements: [arr removeObject: @"lili"]; 6. Remove the last element: [Arr RemoveLastObject]; 7. Removes all elements: [arr removeObjects];


NSNumber *number1 = [NSNumber numberWithInt: 10]; NSNumber *number2 = [NSNumber numberWithInt: 20]; NSNumber *number3 = [NSNumber numberWithInt: 30]; NSNumber *number4 = [NSNumber numberWithInt: 40]; NSArray *arr = @[number1, number2, number3, number4] for (NSNumber *num in arr) {NSArray (@"%D", num.intValue); NSNumber *number1 = @10; int num = 10; NSNumber *n1 = @(num);


Create ways: NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndkeys: @ "jack", @ "name", @ "18," @ "age", nil]; Abbreviations: NSDictionary * dict = @ {@ "name:" @ "rose", @ "age" : @ "18"}; Print: NSLog(@"%@", dict); Values: dict [name]. dict.count; [dict obejctForKeys: @"age"]; Traverse: for (id key in dict) {NSLog (@ "% @ = % @", key, dict [key]); }

Use block traversal enumerateKeysAndObjectsUsingBlock


Key: new NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObjectsAndkeys: @"jack", @"name", @"18",@"age", nil]; Dict setObject:@" Guangzhou xx street ", forKey: @"address"];

Delete all key-value pairs


Deletes the specified key-value pair

[dict removeObjectForKey: @"age"];


Create NSFileManager *manager = [NSFileManager defaultManage]; 1. FileExistsAtPath judgment under the specified path if the file exists nsstrings * path = @ "/ Users/Apple/deastop/cc. Mp3"; BOOL res = [manager fileExistsAtPath: path]

Pause program sleep

[NSThread sleepForTimeInterval: 10];


1. CGPoint P1; 2. p1.x = 20; p1.y = 30; 2. CGPoint p1 = {20, 30}; 3. CGPoint p1 = {.x = 20, .y = 30}; 4. CGPiont p1 = CGPointMaker(20, 30);


1. CgSize Size; size.x = 20; size.y = 30; 2. CGSize size = {20, 30}; 3. CGSize size = {.x = 20, .y = 30}; 4. CGPiont size = CGSizeMaker(20, 30);


CGRect rect;
rect.origin.x = 20;
rect.origin.y = 30;
rect.size.width = 100;
rect.size.height = 200;


It wraps the structure, like NSNumber;

String and time are converted to each other

Nsdate *date = [Nsdate new]; NSLog(@"%@", date); NSDateFormatter * Formatter = [NSDateFormatter new]; formatter.dateFormatter = @"yyyy-MM-DD HH:mm:ss"; NSString *str = [formatter stringFromDate: date]; NSString *strDate = @ "December 12, 2021 12:12:12, 12 seconds"; NSDateForMatter *formatter = [NSDateFormatter new]; Formatter. DateFormatter = @"yyyy year MM month DD HH HH MM mins ss "; NSDate *date = [formatter dateFromString: strDate];

Time to calculate

NSCalendar gets the various parts of the time object

The singleton pattern