1. Summarize your understanding of the Agreement:
A wants to do something but can’t for some reason, so he makes B follow some of A’s conventions so that B can help A do something. The protocol includes methods that the compliant party B needs to implement and what B can do.
2. ARC automatic reference counting
ARC- Automatic reference counting can be used to manage the use of objects and understand how objects are used. Objects are not released when the object reference count is not 0. Objects are released when the dealloc function is called when the object reference count is 0.
3. How to understand retain/copy/assign/release/autorelease dealloc key word:
Retain increments the object reference count by one, release increments the object reference count by one, and dealloc is called to release the object when the object reference count reaches zero. Copy is to let a and B have their own memory if you don’t want them to share the same memory. Use Assgin when using basic data types. Assgin is a direct assignment that causes the object reference count to increase by one.
(1) Assign: common assignment, which is generally used for basic data types to prevent circular references.
(2) Retain: Retain count, obtain user ownership.
(3) Copy: assigns values to objects. In general, strings use copy. In Foundation, immutable objects use copy.
(4) Nonatomic: non-atomic access, no synchronization, multi-threaded concurrent access will improve performance.
Copy the code
4. Please briefly describe the connection and difference between categories and inheritance and the difference between weak and Assgin:
Both category and inheritance use the original methods and attributes of the parent class. Category extends the parent class, while inheritance retains the attributes and methods in the parent class and implements them according to their own actual situation. Weak is used for various UI controls and agents, and Assgin is used for basic data types. #### inheritance can add, modify, delete methods, and add attributes; ####category can only add attributes;
strong:
@property (nonatomic, strong) NSString *string1;
@property (nonatomic, strong) NSString *string2;
self.string1 = @"String 1";
self.string2 = self.string1;
self.string1 = nil;
NSLog(@"String 2 = %@", self.string2);
Result: String 2 = String 1 Since string2 is an attribute defined by strong, the reference count +1 makes them all point to @"String 1"
weak:
@property (nonatomic, strong) NSString *string1;
@property (nonatomic, weak) NSString *string2;
self.string1 = @"String 1";
self.string2 = self.string1;
self.string1 = nil;
NSLog(@"String 2 = %@", self.string2);
Result: String 2 = null
Since self.string1 and self.string2 point to the same address, and string2 has no retain memory address, and self.string1=nil frees memory, string1 is nil. Pointers declared weak will be assigned nil once the address to which the pointer points is released. This benefit can effectively prevent wild Pointers.
Copy the code
5. Please explain your understanding of the keyword strong and weak and the difference between _unsafe_unretained and weak:
Strong is equivalent to retain increasing the reference count of an object by 1, which prevents the object from being released early in an exception case, resulting in crash. Weak references prevent looping applications from being able to free objects and generating wild Pointers.
Strong is called a strong reference. Using strong in ARC tells the compiler that we will automatically insert retain. Weak is the normal assignment equivalent of manually managing memory assign. _unsafe_unretained is the same as weak. The difference is that weak resets the variable to nil after the directed object is destroyed, preventing wild Pointers and EXC_BAD_ACCESS errors.
6. How to realize ARC and MRC mixed programming:
The targets build Phases option is used to select files that are not compiled by Arc. Compile Sources is used to select files that are not compiled by Arc. To do this, double-click it and enter -fno-objc-arc. If you add MRC + -fno-objc-arc to MRC project, you can add ARC + -fobjc-arc to MRC project
7. Objective-c supports multiple inheritance
Multiple inheritance is not supported because message mechanism name lookup occurs at run time, not compile time, making it difficult to resolve the ambiguity that multiple base classes can cause. Similar functionality to multiple inheritance can be achieved through message forwarding protocol classes.
Are variables private by default in Objective-C? Are methods private by default?
Variables are private by default and methods are public by default.
9.#import””. H and @class+
#import””. H for the import header file, @class+ for the forward reference declaration. Import contains all the information about the class, including entity variables and methods, while @class simply tells the compiler that the name declared after it is the name of the class. How these classes are defined is not a matter of thought for now. 2. In header files, you generally only need to know the name of the referenced class. You don’t need to know its internal entity variables and methods, so you typically use @class in header files to declare that the name is the name of the class. In the implementation class, we use the internal entity variables and methods of the referenced class, so we use #import to include the header file of the referenced class. 3. For compilation efficiency, if you have 100 header files that #import the same header file, or if they are referenced in sequence, such as A — >B, B — >C, C — >D, etc. When the original header file changes, all subsequent classes that reference it need to be recompiled, which can take a lot of time if you have many classes. If you use at sign class, you don’t. 4. If there are cyclic dependencies, such as A — >B, B — >A, including each other with #import, then A compilation error will occur. If the @class is used to declare each other in the header file, there will be no compilation error. So, in general, at sign class is put in interface, just to reference that class in interface, to use that class as a type. In the implementation class that implements this interface, if you need to reference the entity variables or methods of the class, you still need to import the class declared in the @class.
10. Please briefly describe the implementation methods of page value transfer:
Blocks, delegate protocols, notifications, singletons, NSUserDefaults
11. Please briefly describe the difference between deep copy and shallow copy:
The deep copy is going to create a new memory space on the heap and it’s going to create a new object pointer with a different address and the shallow copy is not going to create a new memory space and the pointer is going to be the same as before. The essence of deep copy and shallow copy is that the same address is a shallow copy, and different addresses are a deep copy. Shallow copy is a copy operation that does not actually copy, but another pointer to the same address. After a deep copy operation, a copy is actually made, and the other pointer points to the copied address. ###### Shallow copy: During a copy operation, each layer of the copied object is a pointer copy. ###### Deep copy: During a copy operation, at least one layer of the copied object is object copy. Full copy: In a copy operation, each layer of the copied object is an object copy.
### Shallow copy is like your shadow, you are gone, your shadow is gone; ### Deep copy is like your clone, you are gone, your clone is still in; Note: RETAIN: A shallow copy is always retained. The reference count increments by one at a time. Returns whether the object is mutable and consistent with the copied object. Copy: For a mutable object that is a deep copy, the reference count does not change. For immutable objects that are shallow copies, the reference count is incremented by one each time. Always return an immutable object. MutableCopy: Always a deep copy, reference count does not change. Always return a mutable object. Immutable object: when its value changes, its memory head address changes with it. Mutable object: regardless of whether its value changes, its memory header address does not change with it. Reference count: To make it clear to the user how many owners the object has (i.e. how many Pointers to the same memory address).
12. Which objects in the system are singletons:
NSTimer, NSNotification, UIWindow, UIApplication write singleton note: GCD is not used:
// The singleton pattern is the same as the singleton pattern.
// 1. Disable the constructor (throw an exception when called)
// 2. Provide a class method that returns a unique instance of the class
- (instancetype)init {
@throw [NSException exceptionWithName:@"CDSingleton" reason:@" not allowed to call constructor "userInfo:nil];
// return nil;
}
// This method is private because it does not expose the interface in the. H file
- (instancetype) initPrivate {
if(self = [super init]) {
_value = arc4random();
}
return self;
}
+ (instancetype) sharedInstance {
// Static variables have a global life cycle
static CDSingleton *instance = nil;
// Use synchronized blocks to ensure singletons in multithreaded environments
// Synchronous locking, used in multithreading, can make thread safety
@synchronized(self) {
if(! instance) {
instance = [[self alloc] initPrivate];
}
}
return instance;
}
Copy the code
Using the GCD:
+(instancetype)sharedInstance{
static HCDSingleton *singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[HCDSingleton alloc]init];
});
return singleton;
}
Copy the code
13. Summarize your understanding of the MVC design pattern:
MVC: Model-view-controller Model is responsible for the data task attempt is responsible for the presentation and for the interaction Controller is used to control the attempt
Model: Stores and manipulates data
View: Mainly responsible for displaying data and user interaction
The controller is responsible for associating the Model with the View:
Get data from the network -> assign to the data model -> pass the model's data to the view display (in response to the View's delegate and datasource methods)-> refresh the View
Copy the code
14. What technologies in IOS fit the Observer model:
Key-value Observing, which provides a mechanism for Observing, when the properties of a specified object are modified, the object will receive notifications. KVO automatically notifies the corresponding observer each time the properties of the specified observed object are modified.
Definition in model:
@interface StockData : NSObject { NSString * stockName; float price; }
@end
@implementation StockData
@end
Copy the code
Controller, which is basically saying to the model, I want to listen to your update broadcast
- (void)viewDidLoad{
[super viewDidLoad];
stockForKVO = [[StockData alloc] init];
[stockForKVO setValue:@"searph" forKey:@"stockName"];
[stockForKVO setValue: @ "10.0" forKey: @ "price");
[stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
myLabel.textColor = [UIColor redColor];
myLabel.text = [stockForKVO valueForKey:@"price"];
[self.view addSubview:myLabel];
UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 30);
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
Copy the code
The user clicks a button in the View to invoke the action in the controller to change the data in the model
-(void) buttonAction{
[stockForKVO setValue: @ "20.0" forKey: @ "price");
}
Copy the code
The controller needs to implement a callback equivalent to what I should do when I receive a broadcast
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
myLabel.text = [stockForKVO valueForKey:@"price"];
}
}
Copy the code
Note that when using notifications and KVO, always remember to remove, otherwise it will cause a crash
The dealloc view needs to cancel the observation
- (void)dealloc{
[super dealloc];
[stockForKVO removeObserver:self forKeyPath:@"price"]; [stockForKVO release];
}
Copy the code
15. Summarize your understanding of the factory methodology:
When we create an object, we usually alloc one object, and if we need to create 100 of these objects, if we’re in a for loop it’s nice to just say alloc, but it doesn’t work that way, we might create the object in different places, so we might have to say 100 alloc, But if we want to add a fixed value to one of the properties of the object after it is created, for example, the students of the school of something, then we might need 100 more lines of code. If we say -(void)createObj, It’s a lot easier to write the create object and the school property in this method, which means we can alloc the create object and wrap it in a method that we can call directly, which is the simple factory method.
16. What is proxy mode and what needs to be paid attention to to implement proxy:
Agency model: Help others to complete tasks entrusted to you. You need to pay attention to the commitments that others make to you and your ability to accomplish them.
17. Describe the relationship and differences between StoryBoard and Xib:
The StoryBoard can build the entire project interface on it, and the relationship between each controller can be clearly seen. The XIB can implement a complex UI with custom elements and good reuse of components.
18. Please describe how UITableView reuses cells:
For example, a screen can hold 5 UITableView cells, and a total of 6 set CELL reuse markers will be created. Once they can be reused, they can not be reused to create more, reducing memory consumption.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"healthNewsTableViewCell";
healthNewsTableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (! cell) {
cell = (healthNewsTableViewCell*)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: @"healthNewsTableViewCell"];
}
return cell;
}
// Write the data binding in WillDisPlayCell
// The method to make the UITableView slightly smoother is called before displaying the cell
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
healthNewsTableViewCell *MyCell = (healthNewsTableViewCell *)cell;
MyCell.model = dataArray[indexPath.row];
MyCell.backgroundColor = [UIColor colorWithRed:0.936 green:0.941 blue:0.936 alpha:1.000];
}
Copy the code
19. How to use UIScrollView to load multiple images infinitely:
Write an NSTimer every 0.5 seconds execute the following callback method changPic If the number of pictures is limited perform an if judgment when the total number of pictures exceeds, display the first one, restart display from the first one.
20. Please briefly describe the life cycle of the attempted controller:
##### When a view controller is created and displayed on the screen. Init (initWithNibName) initializes the object and initializes the data. 3. LoadView loads the view from NIB. 4. ViewDidLoad is done, you can customize data and dynamically create other controls 5. ViewWillAppear will appear before the screen, The viewDidAppear view has been rendered on screen ##### The order in which a view is executed when removed from the screen and destroyed, ViewDidDisappear is removed from the screen and the user can’t see it anymore. Dealloc is destroyed. Here you need to release the objects that you created in init and viewDidLoad
21.UITableView optimization methods:
1. Images are loaded asynchronously, such as SDWebImage. 2. Use the reuseIdentifier. Static NSString *CellIdentifier = @”XXX”; 3. Write the data binding in the WillDisPlay protocol method. 4. Minimize the use of opaque views in the CELL. 5. If it is not necessary, reduce the use of all reloadData cells.
22. Summarize the event delivery mechanism in IOS:
For example, if the view is the view of the controller, it is passed to the controller. If not, it passes it to its superview at the top level of the view hierarchy, and if it can’t process the event or message it receives, it passes the event or message to the Window object for processing. If the Window object doesn’t process either, Then it passes the event or message to UIApplication object. If UIApplication can’t handle the event or message either, it drops it ##### Note: Why manage events in queues instead of stacks? Queue first in, first out ensures that the event generated first is processed first. Stack first, then out.
UITableView has some data source methods that must be implemented:
// Get the number of cells the section contains
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
/ / create a UITableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
Copy the code
// Implement data source methods as appropriate:
// The number of groups in TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
// The header of the group
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
// The header at the end of the grouping
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
Copy the code
I'm used to binding data to the model in this approach
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
Copy the code
24. Describe the differences between GET and POST requests in Http:
Get gets data from the server, and POST sends data to the server
GET has low security and POST has high security. Because GET is in transit, the data is placed in the requested URL, and many servers, proxy servers, or user agents today record the request URL in a log file and put it somewhere where private information can be seen by a third party. In addition, the user can see the submitted data directly in the browser, and some internal system messages will be displayed in front of the user. All POST operations are invisible to the user. ### Note: A GET request writes parameters directly to the access path. Simple operation, but easy to be seen by the outside world, security is not high, address up to 255 bytes; POST request, put the parameters inside the body. POST request operation is relatively complex, need to separate the parameters and address, but high security, the parameters in the body, not easy to capture.
25. Summarize your understanding of asynchronous request data:
Better user experience by being straightforward: reduce caton’s fake death. Because asynchronous requests for data do not wait for one task to complete before another, other operations can be performed.
26. What technologies are available in IOS to enable threading and how are they related:
First, use @synchronized(self)
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
@synchronized(self)// Use a synchronized guard to ensure that when used by one thread, other threads cannot enter.
{
if (! sharedInstance)
sharedInstance=[[LocationController alloc] init];
}
return sharedInstance;
}
Copy the code
Second, use GCD(Grand Central Dispatch: Macro Center)
When you call dispatch_async, you go through a dispatch queue, and there's a bunch of blocks on that queue, first-in, first-out.
This queue can be created by itself using dispatch_create or by calling the main thread queue dispatch_get_main_queue.
The queue name set up here is onceToken.
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (! sharedInstance)
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
Copy the code
Third, use NSOperationQueue
static LocationController *sharedInstance;
+ (LocationController *)sharedInstance {
NSOperationQueue *onceToken=[[NSOperationQueue alloc] init];
[onceToken addOperationWithBlock:^(){
if (! sharedInstance)
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}];
}
Copy the code
There are three common ways to implement singletons:
- ####NSThread: You can create NSThread in either of the following ways:
// There are two ways to create an NSThread:
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
NSThread* myThread = [[NSThread alloc] initWithTarget:selfselector:@selector(myThreadMainMethod:)object:nil];
[myThread start]; // Start the thread
Copy the code
The difference between the two methods is that the former method creates a thread to do things immediately upon being called; The latter one, although you alloc and init it, doesn’t actually create the thread until we manually call start to start it. This idea of deferred implementation is useful in many resource-related areas. In the latter way, we can also configure the thread before starting it, such as setting the stack size, thread priority. In addition to an indirect way: by using the method of NSObject performSelectorInBackground: withObject: to create a thread:
[myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil];
/ / run in the background a method the effect with NSThread detachNewThreadSelector: toTarget: withObject: is the same.
Copy the code
- ####NSOperationQueue
@interface ViewController () {
// Operation queue
NSOperationQueue *queue;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Concurrent queue (operations in queues are executed concurrently)
queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 5;
for (int i = 0; i < 5; i++) {
CDCar *myCar = [[CDCar alloc] initWithX:20 + 70 * I andY:10]
[myCar draw:self.view];
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[myCar run];
}];
[queue addOperation:op];
}
}
@end
Copy the code
- ####GCD
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// Time-consuming operations such as network data requests
});
dispatch_async(dispatch_get_main_queue(), ^{
// Update the interface
});
Copy the code
How do threads communicate with each other in nsthreads?
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// Time-consuming operations such as network data requests
});
dispatch_async(dispatch_get_main_queue(), ^{
// Update the interface
});
Copy the code
29. What technologies in IOS can ensure thread safety:
1. Use mutex. The mutex format is used
@synchronized
{
// The code to lock
}
Note: locking one piece of code takes only one lock. Multiple locks do not work
Copy the code
- The advantages and disadvantages of the mutex Advantages: can effectively prevent for multithreaded plundered resources data security problem caused by the faults: need to consume large amounts of CPU resources mutex use premise: multiple threads plundered the same piece of resources related terms: thread synchronization, multiple threads in order to perform a task The mutex, is to use thread synchronization technology
OC defines properties with nonatomic and atomic options atomic: atomic, locks setter methods (atomic by default) Nonatomic: does not lock setter methods
@property (assign, atomic) int age;
- (void)setAge:(int)age;
{
@synchronized(self)
{
_age = age;
}
}
Copy the code
- Atomic vs. Atomic properties Selection NonAtomic vs. Atomic: Thread-safe, consumes a lot of resources nonatomic: Non-thread-safe, suitable for small memory mobile devices
30. What is the parent of ASIHttpRequest:
ASIHTTPRequest is an extremely robust open source project for HTTP access. Let simple apis perform complex functions such as asynchronous requests, queue requests, GZIP compression, caching, breakpoint continuation, progress tracking, upload files, HTTP authentication.
It is an extension of NSOperationQueues, small and powerful.
But it is also slightly different from its parent.
For example, adding to a queue does not actually execute the request, only a call to [Queue Go] does;
A running queue does not need to be called [Queue Go] repeatedly.
By default, if a request in the queue fails, it cancels all outstanding requests.
You can set [queue setShouldCancel];
Copy the code
31. Briefly describe the implementation principle of AFNetWork:
AFNetwork is a lightweight network request API class library. It is based on NSURLConnection, NSOperation, and other methods.
- Basic use of AFNewWork: // Create a download task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
Copy the code
// Create an upload task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject); }
}];
[uploadTask resume];
Copy the code
// Upload task with progress
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue. // You are responsible for dispatching to the main queue for UI updates dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
}); } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}}];
[uploadTask resume];
Copy the code
// A task that requests data
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}}];
[dataTask resume];
Copy the code
32. What does Block do?
void (^block)() = ^(){}; // Save a piece of code
/ / definition:
typedef void (^Block)();
@property (strong,nonatomic) Block
Copy the code
Blocks are anonymous functions without names, similar to function Pointers in C.
.h
// Define a Block property (to hold a callback code)
// Property modifiers must write copy because blocks are copied from the stack to the heap
@property (nonatomic, copy) void(^myBlock)(NSString *);
Copy the code
.m
- (IBAction)buttonClicked:(id)sender {
if (_myBlock) {
// Calling Block syntax is the same as calling C functions
_myBlock([NSString stringWithFormat:@" hello, %@", _namefield.text]);
}
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@" Back to first view Controller!!" );
}];
}
Copy the code
// First page (receive page)
.m
- (IBAction)buttonClicked:(UIButton *)sender {
CDSecondViewController *secondVC = [[CDSecondViewController alloc] init];
// Assign the Block variable to the second view controller
secondVC.myBlock = ^(NSString *str) {
_myLabel.text = str;
};
[self presentViewController:secondVC animated:YES completion:^{
// NSLog(@" Get the second view controller!!") );
}];
}
Block:
#import "ViewController.h"
typedef void (^otherBlock) ();
typedef void(^ResultBlock)(BOOL suc,NSString *plat,NSString *info);
@interface ViewController ()
// Attribute defines block
@property (nonatomic,copy) void(^someBlock)();
/ / alias definition block
@property (nonatomic,copy) otherBlock oBlock;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)getDataFromServerWithResult:(otherBlock)oBlock{
}
-(void)getData:(ResultBlock)shareBlock{
}
- (void)pullDownRefreshWithFinishedCallBack:(void(^)())finishCallBack{
}
@end
Copy the code
33. Describe the differences between TCP and UDP:
TCP transmission reliability is guaranteed, it has a three-way handshake mechanism, this mechanism to ensure the verification of data, to ensure his reliability. UDP doesn’t exist, so it’s unreliable. But UDP speed is TCP than, and UDP response speed is faster, QQ is using UDP protocol transmission, HTTP is using TCP protocol transmission.
34. How to ensure more power-saving positioning:
DesiredAccuracy, this attribute is used to control the positioning accuracy. The higher the accuracy is, the higher the power consumption is, so the value of this attribute should be set according to the actual situation.
35. Briefly describe the realization principle of SDWebImage:
- SDWebImage loading process:
Entrance setImageWithURL: placeholderImage: options: first, according to the placeholderImage then SDWebImageManager according to URL starts processing images.
2. Enter the SDWebImageManager - downloadWithURL: delegate: options: the userInfo:, To SDImageCache download cache lookup images are from queryDiskCacheForKey: delegate: the userInfo:.
3. The first pictures from memory cache to find if there is a picture, if have image cache in memory, SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo: to SDWebImageManager.
4. SDWebImageManagerDelegate callback webImageManager: didFinishWithImage: to UIImageView + WebCache front-end display pictures, etc.
5. If the image is not in the memory cache, NSInvocationOperation is generated and added to the queue to find whether the image is cached from the disk.
6. Try to read the image file in the disk cache directory according to the URLKey. This step is performed in NSOperation, so the result callback to the main thread is notifyDelegate:.
7. If the image is read from the hard disk in the previous operation, add the image to the memory cache. (If the free memory is too small, the memory cache will be emptied first.) SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo:. Then call back to the display image.
8. If you do not read from the hard disk cache directory images, point out the picture does not exist in all cache, need to download the pictures, the callback imageCache: didNotFindImageForKey: the userInfo:.
9. Share or rebuild a download SDWebImageDownloader to start downloading images.
10. The image download is done by NSURLConnection, and the related delegate is implemented to judge the image download, download completion and download failure.
11. The connection: didReceiveData: use ImageIO made according to the pictures download progress load effect.
12. The connectionDidFinishLoading: data download is completed to SDWebImageDecoder do image decoding process.
13. Image decoding is done in an NSOperationQueue without slowing down the main thread UI. If there is a need to download images for secondary processing, it is best to do it here, much more efficient.
14. In the main thread notifyDelegateOnMainThreadWithInfo: declare decoding, imageDecoder: didFinishDecodingImage: the userInfo: Callback to SDWebImageDownloader.
15. ImageDownloader: didFinishWithImage: callback told SDWebImageManager pictures download is complete.
16. Notify all downloadDelegates that the download is complete, call-back to display the image where it is needed.
17. Save the image to SDImageCache. The memory cache and hard disk cache save the image simultaneously. Writing files to hard disk is also done as a separate NSInvocationOperation to avoid slowing down the main thread.
18.SDImageCache registers some message notifications during initialization, clears the memory image cache during memory warnings or backlogs, and clears expired images at the end of the application.
19.SDWI also provides UIButton+WebCache and MKAnnotationView+WebCache for easy use.
20.SDWebImagePrefetcher can download images in advance for subsequent use.
Copy the code
36. Outline the advantages of XML and JSON data:
(1) Readability. JSON and XML are almost the same in terms of data readability. JSON and XML are comparable in terms of readability, with recommended syntax on the one hand and canonical tag form on the other, while XML is more readable. (2) Scalability. XML is naturally extensible, JSON certainly is, and there’s nothing that XML can scale that JSON can’t. (3) Coding difficulty. XML has a wealth of coding tools, such as Dom4j, JDom, JSON also has the tools provided by Json.org, but JSON coding is significantly easier than XML, even without the help of tools can also write JSON code, but to write GOOD XML is not easy. (4) Decoding difficulty. XML parses with child and parent nodes, which is mind-numbing, while JSON is almost zero difficulty. This is a bad point for XML. (5) Popularity. XML is already widely used in the industry, while JSON is just getting started, but in this particular area of Ajax, XML must take a back seat to JSON in the future. Ajax should then become Ajaj(Asynchronous Javascript and JSON). (6) Analytical means. JSON and XML also have rich parsing tools. (7) Data volume. JSON is smaller and faster than XML. (8) Data interaction. JSON interaction with JavaScript is more convenient, easier to parse, better data interaction (9). Data description. JSON is less descriptive of data than XML. (10) transmission speed. JSON is much faster than XML.
37. Briefly describe the connection and difference between threads and processes:
I read a blog post about threads and processes, and I quote it here:
1. The core of the computer is the CPU, which undertakes all the computing tasks. It’s like a factory, always running. 2. Assume that the plant has limited power to supply only one workshop at a time. That is to say, when one workshop starts, all the others must stop. The implication is that a single CPU can only run one task at a time. 3. Processes are like factory floors, representing individual tasks that the CPU can handle. At any one time, the CPU is always running one process and the other processes are not running. There can be many workers in a workshop. They work together on a task. Threads are like workshop workers. A process can contain multiple threads. 5. The space of the workshop is shared by workers, for example, many rooms are accessible to each worker. This indicates that the memory space of a process is shared, and each thread can use the shared memory. However, each room is of a different size. Some rooms, such as toilets, can only hold one person at most. When there are people inside, no one else can get in. This means that when a thread uses some shared memory, other threads must wait for it to finish before they can use it. 7. An easy way to keep people out is to add a lock to the door. Those who arrive first lock the door, and those who arrive later, when they see the lock, line up at the door and wait for the lock to open before they enter. Known as “Mutual exclusion,” or Mutex, this prevents multiple threads from simultaneously reading and writing an area of memory. 8. There are also rooms that can accommodate more than one person at a time, such as the kitchen. In other words, if the number of people is greater than n, the extra people have to wait outside. This is like some memory area that can only be used by a fixed number of threads. 9. The solution is to hang a bunch of keys at the door. He who goes in takes a key, and hangs it back on his way out. When the last person to arrive finds his keys on the rack, he knows he must wait in line at the door. This practice, called Semaphore, is used to ensure that multiple threads do not conflict with each other. It is not hard to see that mutex is a special case of Semaphore (when n=1). In other words, you can replace the former with the latter. However, because of mutex’s simplicity and efficiency, this design is used in cases where resource exclusivity must be guaranteed.
38. Briefly describe the usage scenarios and precautions of NSUserDefaults:
So NSUerdefaults is generally used to store user preferences like login accounts and passwords and things like that. We can also use it to store images, strings, numbers and objects. It is saved in the Plists file in the project. There are two methods that you can use to save an image, you can use PNG or JPG to convert it to NSData and then use NSUerdefaults and when you save it you use Synchronize in order to save it immediately. It can also be used to pass values back between programs.
39. What technology is used to implement the database in IOS:
Sqlite 3
40. Describe what a primary key is and what a foreign key is:
A primary key is a unique marker used to uniquely identify a record, such as an id number. A foreign key is used to associate other tables, and a field on another table can be uniquely identified by this foreign key. For example, if A field in table A is the primary key in table B, this field is the foreign key of A.
How to store data model in IOS:
The SandBox mechanism in IOS is a security system that states that an application can only read files in the folder created for that application, and cannot access content elsewhere. This is where all non-code files are stored, such as images, sounds, property lists, text files, etc. 1. Each application is in its own sandbox. 2. You cannot cross your own sandbox to access the contents of other application sandboxes. Permission authentication is required for applications to request or receive data
43. How to implement real machine debugging:
Xcode7 can be tested on real machines without the developer certificate
44. How to find memory leaks in a project:
Use Instruments to find memory leaks in programs, and NSZombieEnabled.
45. How to realize the payment link in the project:
Notice The Apple ID needs to be configured. Others need to be configured according to the wechat Pay or Alipay document
47. Briefly describe the problems you have encountered in the project:
When I was working on a project, AMap was used in the project. At that time, every time I clicked into a cell, I would enter the map. Later, I found that the program would crash when the speed of clicking and exiting was accelerated. After a long search, I realized that every time you created a map, it would take up a lot of memory, and every time you quit before you finished creating a map, it would crash, so I finally moved the map creation part of the code to the create cell (in the previous page), so that there was only one map at a time. It will not crash because the map has not been created.
Self. name= XXX and _name= XXX
(1)self.name has getter and sett er methods. (2)self.name can be heard by KVO (set method and KVC method). (3)self.name considers memory management as an object pointer
The former is calling the setter method, the latter is plain assignment.
50.#include / #import / @class
#include and #import have the same effect, except that the latter does not cause cross-compilation, ensuring that headers are imported only once. Import imports all the information about a class, including variables and methods, while @class tells the compiler that the following name is the name of the class. #import is recommended for more efficient compilation and to prevent compilation errors involving each other.
1. Does IOS support garbage collection mechanism?
IOS development only supports manual memory management and ARC. Mac development supports GC garbage collection. GC was deprecated after 10.8 and ARC is recommended.
2. How to copy a user-defined object (mutable and immutable copy)
One must implement the copying and mutableCopying protocols to return an immutable and mutable object. Otherwise, an exception will occur in the program.
-(id)copyWithZone:(NSZone*)zone{
Person *person = [[self Class] allocWithZone:zone];
person->age = self.age;
person->name = self.name;
return person;
}
Copy the code
-(id)mutableCopyWithZone(NSZone*)zone;
Copy the code
3. Why call [super dealloc] when releasing objects:
Because subclasses inherit from the parent class, some objects (instance variables) in subclasses also inherit from the parent class, so we need to call methods of the parent class to release instances owned by the parent class.
4. Briefly describe common design patterns:
Singleton design, agent design, observer (notification), factory method.
= self.xxx = nil = self.xxx = nil = self.xxx = nil
It’s good to use self. XXX = nil because it calls release first and sets the variable to nil, so it’s safer to release the object and prevent wild pointer calls.
6. Concept of event responder chain:
A responder chain represents a series of responder objects. The event is handed to the first responder for processing, and if it is not handled by the first responder, the event is passed up the responder chain to the next responder. Typically the first responder is a view or its subclass, and when it is touched the event is handed to it for processing. If not, the event is passed to its view controller (if present), then to its superview (if present), and so on up to the top level view. And then we’re going to go from the top view to UIWindow to UIApplication. If the entire procedure does not respond to the event, the event is discarded.
Static variable and static function:
(1) Static variable indicates that a variable is stored statically and stored in a static storage area. (2) added before the function indicates that the function is an internal connection, only valid in this file, other files can not apply the function.
Static global variables are used only once to prevent them from being referenced in other file units. A static local variable is initialized only once, and the next time it is initialized is based on the last value. What is the difference between a static function and a normal function :static functions have only one copy in memory, while normal functions maintain one copy for each call
8. Three pillars of object Orientation and how to understand dynamic binding (polymorphism) :
Three pillars: encapsulation, polymorphism, and inheritance polymorphism: inheriting parent classes, implementing methods, looking at objects instead of Pointers, and different objects implementing different methods that they override.
9. The difference between frame and bounds:
(1)Frame: The view is the position and size in the parent view coordinate system (the reference point is the parent view’s coordinate system). When the View is transformed, the value is inaccurate. (2) Bounds: This view is the position and size of its own coordinate system (the reference point is its own coordinate system).
10. Runloop:
Run loop is part of the thread-specific infrastructure. A run loop is an event processing loop that continuously dispatches work and processes input events. The purpose of using run loop is to keep your thread busy when it is working and dormant when it is not.
11.SVN and Git collaborative development, how to prevent code file conflicts:
(1) To prevent code conflicts: do not modify the same file at the same time. For example, both USER A and user B modify A file at the same time. User A first modifies the file and then submits it to the server. Then user B updates the file and modifies it. (2) The project file XcodeProj on the server only allows one person to manage the submission, while others only update. Prevents conflicts with this file.
12. How to implement breakpoint continuation:
The downloaded file is divided into several parts, through the HTTP protocol request header, set the offset of each part of the download, and then download each part through multi-threading, and then compose the final complete file after downloading.
13. Heap vs. stack and queue vs. stack:
The stack area is automatically allocated and released by the compiler. The parameter values of the method (function), the value of local variables, etc. The heap area is generally allocated and released by the programmer. If not released, the memory overflow. Queue: First in first out Stack: First in last out
Understanding of Agreement and Agency:
This is actually A call between two objects. Class A, class B, objects with B in class A, b.delegate =A
15.HTTP, TCP, and UDP
Data request: status line, request header, request body Server response: response header (status code: 200; 404 Resource not found 400 Client request syntax error; 500 server error;) Response body W3C School online tutorial
16.IOS 6 differs from IOS 7:
IOS 6 Skeuomorphic IOS 7 Flat style
17. What is a pointer:
type *p; Type: indicates the type of the class data. The number pointer used to store the memory unit is not exactly equal to the address! Typed Pointers that identify many types: data, methods, void. Sizeof may be different for different compilation environments.
Write a macro that returns the smaller of two arguments:
#define MIN(a,b) ((a)>(b)? (b):(a))
Copy the code
19. Sorting algorithm: #### select sorting
-(void)bunbleSort:(NSMutableArray *)aData{
int count = 0;
for(int i = 0; i < [aData count]-1; i++)
{
for(int j = i+1; j < [aData count]; j++)
{
if([[aData objectAtIndex:i] integerValue] < [[aDataobjectAtIndex:j]integerValue])
{
NSNumber *temp = [aData objectAtIndex:i];
[aData replaceObjectAtIndex:i withObject:[aData
objectAtIndex:j]];
[aData replaceObjectAtIndex:j withObject:temp];
count ++; }
}}
}
Copy the code
#### bubble sort
-(void)sort2:(NSMutableArray *)resource{
/ / NSNumber small - >
int count = [resource count];
for(int i = 0; i < count-1; i ++)
{
for(int j = 0; j < count-i-1; j ++)
{
if([[resource objectAtIndex:j] integerValue]>[[resource objectAtIndex:j+1] integerValue])
{
NSNumber *temp = [resource objectAtIndex:j];
[resource replaceObjectAtIndex:j
withObject:[resource objectAtIndex:j+1]];
[resource replaceObjectAtIndex:j+1
withObject:temp];
}
}}
}
Copy the code
#### quicksort
-(void)quickSortWithArray:(NSMutableArray *)aDataleft:(NSInteger)left right:(NSInteger)right
{
if (right > left) {NSInteger i = left;
NSInteger j = right + 1;
while (true) {
while (i+1 < [aData count] && [aData objectAtIndex:++i] <[aData objectAtIndex:left]) ;
while (j-1 > -1 && [aData objectAtIndex:--j] > [aDataobjectAtIndex:left]) ;
if (i >= j)
{
break;
}
[self swapWithData:aData index1:i index2:j];
}
[self swapWithData:aData index1:left index2:j];
[self quickSortWithArray:aData left:left right:j-1];
[self quickSortWithArray:aData left:j+1 right:right];
}
}
-(void)swapWithData:(NSMutableArray *)aDataindex1:(NSInteger)index1 index2:(NSInteger)index2
{
NSNumber *tmp = [aData objectAtIndex:index1];
[aData replaceObjectAtIndex:index1 withObject:[aDataobjectAtIndex:index2]];
[aData replaceObjectAtIndex:index2 withObject:tmp];
}
Copy the code
20. Write a single linked list that allows you to insert and delete data:
struct QFInfo{
int num;
struct QFInfo *next;
};
struct QFInfo *qfinfo;
/ / head
void insert_AtFirst(struct QFInfo *head,struct QFInfo *insert)
{
insert->next = head->next;
head->next = insert;
}
/ / list the tail
void insert_AtEnd(struct QFInfo *head,struct QFInfo *insert)
{
struct QFInfo *temp = head->next;
while (temp->next ! = NULL) {
temp = temp->next;
}
insert->next = NULL;
temp->next = insert;
}
/ / delete
void delete_1(struct QFInfo *head,struct QFInfo *del)
{
struct QFInfo *temp = head->next;
while (temp->next ! = NULL && temp->next ! = del)
{
temp = temp->next;
}
if(temp->next ! = NULL)
{
temp->next = temp->next->next;
}
}
Copy the code
21. What are the three retaincounts in the following program and why?
NSMutableArray *arr = [[NSMutableArray array] retain];
NSString *str = [NSString stringWithFormat:@"test"];
[str retain];
[arr addObject:str];
NSLog(@"%@%lu",str,[str retainCount]);
[str retain];
[str release];
[str release];
NSLog(@"%@%lu",str,[str retainCount]);
[arr removeObject:str];
NSLog(@"%@%lu",str,[str retainCount]);
The values are 3, 2, and 1, because retain is 1 when initialized, +1 when retained, +1 when added to array, -1 when released, and -1 when removed from array.
Copy the code
22. The difference between references and Pointers:
1. A pointer can change the value to which it points at run time, but a reference does not change once bound to an object. Reference access to a variable is direct access, whereas Pointers are indirect access. 2. From the perspective of memory allocation: the program allocates memory regions for pointer variables, but references do not allocate memory regions. 3. From the perspective of compilation: during compilation, the program adds Pointers and references to the symbol table respectively, and the symbol table records variable names and their corresponding addresses. The address value of a pointer variable on the symbol table is the address value of the pointer variable, and the address value of a reference on the symbol table is the address value of the reference object. The symbol table is created and never changes, so Pointers can change the object to which they point (the value in a pointer variable can change), but reference objects cannot.
23. How to add pictures to an album:
UIImage *img = [UIImage imageWithNamed:@ "123.ppng"];
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
Copy the code
24. Write a method to get the date in the format 2016-08-08:
NSDate *date = [NSDate date];
NSDateFormatter *dateFm = [[NSDateFormatter alloc] init];
dateFm.dateFormat = @"yyyy-MM-dd";
NSString *dateStr = [dateFm stringFromDate:date];
NSLog(@"dateStr:%@",dateStr);
Copy the code
25. Permanently saving a set of data to your phone:
NSUserDefaults, PList, databases, plain files, archives
26. NSarray * array = @ [@ “a” @ “b”, @ “c” @ “a”, @ “d”… Select * from array where there are N string elements;
(Analysis: Remove duplicate elements and concatenate them into a string)
Example code:
NSArray *arr = @[@"a",@"b",@"b",@"c"];
NSString *resultStr = [arr objectAtIndex:0];
for (NSString *str in arr)
{
if ([resultStr rangeOfString:str].location == NSNotFound) {
resultStr = [resultStr stringByAppendingString:str];
}
}
NSLog(@"%@",resultStr);
Copy the code
27. Write an example of Block usage that illustrates the syntax and advantages of Block programming as much as possible:
void(^myBlock)(NSString *msg);
myBlock = ^(NSString *str){
NSLog(@"%@",str); //line3
}
/ / use the block
// Put the line3 code here to execute.
myBlock(@"hello!" );
Copy the code
28. What is the difference between nil and NULL?
Nil is an object, NULL is a value
29. When to use NSMutableArray and when to use NSArray:
NSMutableArray is used for things that need to change while the program is running, and NSArray is used for things that don’t change when the array is initialized. Note that the use of NSArray only means that the array does not change at run time. That is, you cannot add or delete elements to the array of NSAarry, but it does not mean that the contents of the elements in the array cannot change. NSArray is thread-safe, NSMutableArray is not thread-safe, multithreading using NSMutableArray has to be careful.
30. If we do not create a memory pool, is there a memory pool available to us:
The interface thread maintains its own memory pool, and the data thread created by the user needs to create its own memory pool.
31. Methods of class NSObject are often used:
NSObject is the base class of Objetive-C, which consists of the NSObject class and a set of protocols. The class method alloc, class, object description method init, dealloc, – performSelector: withObject: afterDelay: etc are often used.
32. What is a predicate:
Predicate is through NSPredicate, is through the given logical conditions as constraints, to complete the screening of data.
predicate = [NSPredicate predicateWithFormat:@"customerID == %d",n];
a = [customers filteredArrayUsingPredicate:predicate];
Copy the code
33. Brief description of memory partitions:
2). Data area: memory is applied and initialized when the system is running, and released by the system when the system exits. Storage of global variables, static variables, constants 3). Heap area: through malloc and other functions or operators such as new dynamic application, programmers need to manually apply and release 4). Stack area: function module application, the end of the function by the system automatically released. Store local variables, function parameters