Usually develop their own records, will continue to update and supplement to this article, the relevant knowledge points will not be discussed, mainly means about this thing, as usual their own records, convenient work query

MRC related

  • MRC dealloc, when it frees the property memory self.xxx = nil it doesn’t release, because set will release the old value and then assign the new value

  • Retain a new value from the MRC

  • MRC ARC class, use autoRelease, otherwise ARC class will not be released

  • Alloc init copy Mutablecopy new returns an object that has a reference count of one, so externally you need to do memory management on it, and otherwise you return an autoRelease object, which of course is apple’s programming specification, Usually we custom methods also follow this specification

  • Local variable creation plus autoRelease, global variable delloc nil

  • Print the reference count under ARC

    NSObject *test = [NSObject new];
    NSLog(@"%p".test);
    NSLog(@"1 = = % @"[test valueForKey:@"retainCount"]);
    
    _ref = test;
    NSLog(@2 = = % @ ""[test valueForKey:@"retainCount"]);
    
    self.delegate = test;
    NSLog(@"3 = = % @"[test valueForKey:@"retainCount"]);
    
    NSLog(@"%p",self.delegate);
Copy the code

UITableView related

  • CellForRowAtIndexPath Is not executed

1. The dataSource and delegate are not set

NumberOfRowsInSection and numberOfRowsInSection return data that is not an integer greater than 0

3. The tableView is not added to the superview

  • UITableView ReloadData jitter, flash

1. Eliminate high budgets

    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
Copy the code

2. Reload only one line or cell

  [self reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
  
    [self reloadRowsAtIndexPaths:@[
                                   [NSIndexPath indexPathForRow:0 inSection:0]
                                   ] withRowAnimation:UITableViewRowAnimationNone]
Copy the code

3. No animated reloadData

[UIView performWithoutAnimation:^{
        [self reloadData];
    }];
Copy the code

4. Use this if reloadData is just for adding new data

- (void)insertRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
Copy the code

5. Custom cell, using SDWebImageView, after downloading the image callback, call back and then asynchronously layout

6.UItableView set to Grounp will automatically offset 64, set tableHeaderView height can not be 0

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
Copy the code

7. Set the time for the scroll bar to appear or always appear

8. When set to group, white space appears at the end, and the footerView height is set to CGFLOAT_MIN, corresponding view Return nil

  1. Deselect cell

cell.selectionStyle = UITableViewCellSelectionStyleNone;

10. Remove the dividing line

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone
Copy the code

Messy Tip

  • Under the ARCdeallocI don’t have to write inside[super dealloc]Because the editor adds it automatically at run time
  • <# code block appears #>
  • I just updated the iPhone system, open the Settings, you can’t see the developer option, this will be connected to Xcode will appear
  • If the code inside the block is long, it should be encapsulated to avoid too long code, forget to use WeakSelf, which leads to circular reference
  • UICollectionView does not go to the datasource agent
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *) indexPath reason is the inheritance of ` UICollectionViewFlowLayout ` class ` init ` method of setting the ` itemSize ` it got a negative width negative self. The itemSize = CGSizeMake(width, width);Copy the code
  • Export xcode custom code blocks
Xcode in blocks of code stored by default in ~ / Library/Developer/Xcode/UserData/CodeSnippets, can copy out directly, in a new computer that directoryCopy the code
  • Classification can not add instance variables, and can’t because classification is not a real class, class is the essence of a structure, there is a corresponding pointer to point to the corresponding property list, the list of methods and so on, but the essence of the classification is also a structure, but the structure without this pointer to a list of attributes, So classifications don’t have this structure to store instance variables

  • Resolve asynchronous callbacks

If there is a method that has asynchronous callbacks, then we can solve this problem with GCD groups and semaphores, and recursionCopy the code
  • Pod official provides public hooks (address: guides.cocoapods.org/syntax/podf…). Podfiles are Ruby, so you can change them as you like. www.rubydoc.info/gems/xcodep… This library is cocopods for modifying Xcode configuration files, with API documentation

2. After alloc of the local variable in the method, the pointer cannot be released inside and outside the method because it needs to be passed out. Therefore, autoRelease is used to solve this problem.

3. NSMutableArray automatically retains and releases each time an object is added or removed.

4. StringWithFormat: Returns autoRelease by default, or initializations without manual Release will return AutoRelease by default.

NSString and NSArray property declarations usually replace retain or strong with copy to prevent external modification, while the delegate is mostly declared as weak to prevent cycle retain.

If you inherit from UITableViewController, you can directly use its own tableView, and set the size and other properties; If you inherit from UIViewController, you need to add a tableView and set its delegate and dataSource. PS: Remember not to use xiB, if you delete the XIB file, the previous XIB content is still there!

7, About custom tableViewCell: Set the class of the newly created cell to the corresponding cell class instead of file and owner. Then connect the customized view and controller in the cell to obtain the customized label or button. To use a custom cell, register the custom NIB first and dequeue ereuse it directly. If there is no XIB, you need to define the label in the class file and then create the cell as the default.

8, to set up the cell is selected state of background color, in setSelected: animated set in the cell. The selectedBackgroundView. To change the style of the cell, override layoutSubviews.

9. To perform drawRect, call setNeedsDisplay

10. One of the functions of delegates is to make a program respond correctly to any situation.

11, vibration: join framework AudioToolbox framework import AudioToolbox. H add code: where any vibration AudioServicesPlaySystemSound (kSystemSoundID_vibrate);

12, rewrite the drawRect method: first of all need to get the context UIGraphicsGetCurrentContext (). When painting, fill in the code between UIGraphicPushContext(context) and UIGraphicPopContext() if you need to save the current drawing state.

If a property is associated with the screen, we can override its setters to redraw, i.e. call setNeedDisplay to trigger drawRect. And for efficiency, say in the setter that if(_foo! =foo){ }

Segue create a new View controller,always

NavigationBar backBarItem must precede the parent Controller push code

ViewDidLoad is still the original size of controller.view. If you want to resize it, put it in viewWillAppear next. ViewWillAppear is also good for time-consuming tasks, such as downloading, but open a separate thread.

17. Never let self.view point to anything else except in a loadView. Don’t use loadView whenever you use storyboard or XIB; But overriding the loadView method must set self.view

18, try not to use awakeFromNib, initialization is best placed in viewDidLoad.

Alloc initWithFrame is rarely used. UIImage alloc changes the frame of UIImageView to the size of the image, imageView.image does not.

ScalePagesToFit in webView must be set to YES.

21. Use NSURL instead of NSString to set file names

22. When using scrollView, be sure to set its contentSize. To zoom in, is to set the scrollView. MinimumZoomScale and maximumZoomScale, and achieve its delegate (UIView * viewForZoomingInScrollview) and connection of the delegate.

23. Any object in a block needs a Strong pointer. But this can cause a memory cycle, and the solution is to declare __weak.

24. Anything UIKit related must be done in the main thread.

NSUserDefault stores arrays that contain custom types, then you need to make the custom class implement <NSCoding> 6. About the methodif returnandif else.if elseIt's used to distinguish distinct mutexes,if returnIt's used to handle special error states, andif returnThe advantage is that brevity improves readability if fearif returnIn general, the method is too long. When the method is too long, we should try to extract the code 7 of the method. About recursion, try not to use recursion, have to use recursion also have to add a sign, let him go once, do not go twice, to prevent recursion stuck, of coursewhile8. Try not to beset9. When you customize a cell, keep it in one place instead of looking at two similar cellstype10. Copy the code to be sure to see what the code does, for example, I once was to get all the system font, so a code, but did the database insert, update, so is not suitable for my method getAllSystemFont, So get rid of the database operation 11. Xcode does not run a breakpoint. Xcode does not run a breakpoint. Xcode does not run a breakpoint. Edit scheme -> info, build Configuration changed to Debug, check box before Debug executable Second, in debug mode, xcode does not stop at the breakpoint code and enters the thread solution: debug ->Debug Workflow-> Always show Disassembly check box is turned off. Third, in debug mode, Xcode does not use the POD third-party library breakpoint solution: try clean and rebuild. Either restart Xcode, or delete all breakpoints and add them again. * * *Copy the code
  • The parent class declares method A, and subclasses cannot call method A
  • Oc’s container classes are not inheritable, because container classes use the class cluster design pattern

Tips for resolving bugs encountered

  • Click UICollectionCell, present a page, click close the page, click the cell again, there is no response, click again to get a response; This problem is caused by setting the allowsMultipleSelection property of the UICollectionView to YES, allowing multiple options, causing a second click to trigger the de-selected proxy method

    __block KSOFontInfo *currertFont = nil;
    if (mCurrentFontIndex >= 0 && mCurrentFontIndex < oldFontList.count) {
        currertFont = [oldFontList objectAtIndex:mCurrentFontIndex];
    }
   
    editFontListViewController.willDismissBlock = ^{
        if(! currertFont)return;
        [weakSelf resetWordFontList];
        [mfontList enumerateObjectsUsingBlock:^(KSOFontInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj isKindOfClass:[KSOFontInfo class]]) {// Here currertFont will be wild pointerif([obj.familyName isEqualToString:currertFont.familyName]) { mCurrentFontIndex = idx; *stop = YES; isExist=YES; }}}]; } // currertFont refers to an element in the mfontList array, but after resetWordFontList, the array has been emptied. This leads to the element field pointer // so the Tip for this is, when a pointer points to a place, especially if it's used later in a callback, you need to consider whether it's going to change. You can also consider using copy // and a point, remember if it's MRC, Use autoRelease in copy, this is wrong, this will still be released, should call release after the callback is completeCopy the code
- (void)resetWordFontList
{
    if (mfontList == nil)
    {
        mfontList = [[NSMutableArray alloc] init];
    }
    else{ [mfontList removeAllObjects]; }... }Copy the code

Debugging technique

1

We can also directly use the Watchpoint command in the LLDB, with options to achieve more effects. watchpointset self->testVar // Set watchpoint watchpoint for the variable addresssetExpression 0x00007fB27B4969e0 // Sets the watchpoint for this memory address. The watchpoint can be obtained by using the 'p' command mentioned abovecommand add -o 'frame info'1 // Add subcommand 'frame info' watchpoint list // List all watchpoints watchpoint delete // Delete all watchpointsCopy the code

2

Edit scheme -> info, change the build configuration to DEBUG, and make the check mark before the Debug executable. Second, in debug mode, xcode does not stop at the breakpoint code and enters the thread solution: debug ->Debug Workflow-> Always show Disassembly check box is turned off. Third, in debug mode, Xcode does not use the POD third-party library breakpoint solution: try clean and rebuild. Either restart Xcode, or delete all breakpoints and add them again.Copy the code

3

Print the layer structure Po [[UIWindow keyWindow] recursiveDescription] Print the layer structure of a view Po [[[UIWindow keyWindow] rootViewController] _printHierarchy] Prints stack BT all Prints stack BT all for all threadsCopy the code

Xcode error message

Init methods must return a type related to the receiver type

A method starting with init can return only that object, not any other object type.

Xcode compilation is relevant

1. Obtain the current number of cores: $sysctl -n hw.ncpu 2. Set up the compilation thread count: $defaults write com. Apple. Dt. Xcode IDEBuildOperationMaxNumberOfConcurrentCompileTasks August 3. Get the number of compiled threads: $defaultsreadcom.apple.dt.Xcode IDEBuildOperationMaxNumberOfConcurrentCompileTasks 4. Display the compile time: $defaults write com. Apple. Dt. Xcode ShowBuildOperationDuration YESCopy the code

Working experience

1. In the design of UI components, want to consider to provide external interface is used to modify the state of the UI components, and should not be unilateral thinking, click my UI trigger event stream, other information need to be considered a, from the external events into the UI components, change the UI state, want to consider two-way situation, don’t put the UI components sealing too die

2. Multiple button states:

Click highlight;

Click select, and then click unselect;

Click selected, and then click not to deselect, click other to deselect;

Multiple choice, single choice

Partial multiple selection + partial single selection

3. A UI class exposed to the external UI object, actually a little pit, the external may modify the object, after a long time maintenance is very troublesome, do not know where the external modification, so the external properties of the best readonly, and then provide a block method, out to the external to set, so that after the direct search block method, I know where the outside is, right

4. As for the split screen of iPad, when the screen is narrow, the style of iPhone may be used, and the navigation bar is hidden. When the screen is cut to widescreen, the layout will be rearranged, and the navigation bar will be displayed. Since the navigation bar in the animation is still the iPhone state, you have to do it in a split screen before making a safe layout

5. When assigning an attribute from one class to another, such as AVc attribute Name and AVc view attribute Name, consider that the Name is a pointer to the view, and the view will modify it. If the AVc’s use of Name is affected, For example, you need to pay special attention to the assignment of a Mode past, which requires special attention

6. The header file should not expose too many read and write properties, for example, there is A property view in class A, and then many places to set the view.hidden or other properties of class A. At this time, sometimes it is troublesome to debug. So it’s probably A good idea to expose the interface, and then try to read the properties as much as possible, so that when you’re debugging, when you’re trying to figure out what’s going on with this class A, you can only look at the.m of class A, and you can mostly see what’s going on outside of it, right

7. Do not rely too much on some warning macros, such as API_AVAILABLE(ios12), normally a warning that should be 12 use, but the trap, no warning, resulting in ios11 online crash, so need to use API_AVAILABLE method, it is best to add if return safe point

Init UI processing code, preferably with a safe main thread macro, to prevent external use, such as lazy loading, this situation may be child thread to call, and then crash

9. When modifying a UI property of a class, especially when removing addSubView, pay attention to whether the external view is used as a constraint, because if you remove addSubView, the external view is also used as a constraint, it will crash

10. Thinking about writing UI, before there was a module for sharing and sending, its structure is probably like this, VC chileVc, VC is mainly business logic, jump, chileVc is content view, originally thought it was a good view and logic split. There was a need to add the shared mode as a view to a view. At that time, I added the vc. view, and the effect was visible. But share the click view inside, especially the jump code, like self dismiss… Or the self the present… It’s all based on the fact that Vc is presented. So there is a point to think about here. The disadvantage of this module is that everything is presented based on it. For example, the add View now makes the jump code unservicable, self dismiss… Or the self the present… None of them are valid because Self was not presented. So there’s a point to think about, usually when you write code like this in VC, you can dismiss self… Or the self the present… Write it as self.xxx, which is externally determined to make it more extensible

Easy to forget code

1. Array element execution method

[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
Copy the code

2. PresentedViewController and PresentingViewController distinction

Hypothesis from A controller to jump to B by means of the present controller, then Amy polumbo resentedViewController is B controller; P. resentingViewController is A controller.

Note on official API usage

1.[NSURL URLWithString:urlStr] If urlStr contains Chinese characters or special characters, then calling this method returns nil

Development activities

1. When unplugging the data cable, do not unplug until xcode is broken

Review code main review points

1. Does block use self directly

2. While whether to create an infinite loop

3. Whether an attribute declared as a strong reference is externally assigned or is referenced circularly

4. If the name of the method is changed, is there any change in the place where the method is called, especially when deleting the method, make sure to search for the corresponding call, especially for perforSelect,KVO, and notification listener

5. When putting multiplayer development into storage, keep in mind that the project can be programmed

Not much of an API

IntrinsicContentSize: the built-in size of the control. UILabel, UIButton, they all have their own built-in size. The built-in size of a control is often determined by the content of the control itself. For example, if the text of a UILabel is very long, the built-in size of the UILabel will naturally be very long. The built-in size of the control can be obtained from the UIView’s intrinsicContentSize property. But can be by invalidateIntrinsicContentSize method to recount intrinsicContentSize in UI programming event next time. If you just create a raw UIView object, it obviously has a built-in size of 0.

Thread related

1. If a method’s callback is on a child thread, it can be synchronized using a semaphore

If the callback is the main thread, you can use CFRunLoopRun(); CFRunLoopStop(CFRunLoopGetCurrent()); CFRunLoopStop(CFRunLoopGetCurrent); Stop running empty