Print all subviews of the View
po [[self view]recursiveDescription]
Copy the code
2. Call timing of layoutSubviews call
* Called when the view is first displayed. * Adding a subview also calls this method. * This is called when the size of the view changes. * This is called when the subview's frame changes. * This is called when a subview is deleted.Copy the code
3. NSString filters special characters
/ / define a set of special characters NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString: Selections @ @ / :; "()", "", [] {} - * # % + = _ \ \ | ~ < > $euro ^ • '@ # $% ^ & * () _ +' \" "]; / / filter string of special characters nsstrings * newString = [trimString stringByTrimmingCharactersInSet: set];Copy the code
4. The TransForm property
/ / translation button CGAffineTransform transForm = self. ButtonView. TransForm; self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0); / / rotate button CGAffineTransform transForm = self. ButtonView. TransForm; self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4); / / zoom button self. ButtonView. Transform = CGAffineTransformScale (transform, 1.2, 1.2); / / initialize the reset self. ButtonView. Transform = CGAffineTransformIdentity;Copy the code
5. Remove the dividing line to make it 15 pixels
First add the following code to the viewDidLoad method: if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) { [self.tableView setLayoutMargins:UIEdgeInsetsZero]; } then override the willDisplayCell method - (void)tableView (UITableView *)tableView willDisplayCell (UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { [cell setSeparatorInset:UIEdgeInsetsZero]; } if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; }}Copy the code
6. The calculation method takes time interval
#define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); #define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)Copy the code
7, Color macro definition
#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 Green :arc4random_uniform(256) / 255.0 // color (RGB) #define RGBCOLOR(r, g, B) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1] #define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]Copy the code
8. Alert macro definition
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@" hint "message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@" otherButtonTitles:nil "showCopy the code
8. Exit the iOS app directly
- (void)exitApplication { AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIView animateWithDuration:1.0f animations:^{window.alpha = 0;} completion:^(BOOL finished) {exit(0);}]; }Copy the code
**8, NSArray quickly find the maximum, minimum and average sum **
NSArray * array = [NSArray arrayWithObjects: @ "2.0", @, "2.3" @ "3.0", @, "4.0" @ "10," nil]; CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);Copy the code
9. Modify different text colors in Label
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self editStringColor:self.label.text Color :[UIColor blueColor]]; } - (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color { EditStr is the string to be modified NSRange range = [string rangeOfString:editStr]; NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string]; / / set the UIColor property change font color and size UIFont [attribute addAttributes: @ {NSForegroundColorAttributeName: color} range: the range]; self.label.attributedText = attribute; }Copy the code
10. Play the sound
#import<AVFoundation/AVFoundation.h> // 1. NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"]; NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"] NSURL *tempUrl = [NSURL fileURLWithPath:path]; // 3. Create a player with the converted URL NSError *error = nil; AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error]; self.player = play; // 4. Play [play];Copy the code
11. Check for IPad Pro and other device models
- (BOOL)isIpadPro { UIScreen *Screen = [UIScreen mainScreen]; CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale; CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale; BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad; BOOL hasIPadProWidth = fabs(width - 1024.f) < DBL_EPSILON; BOOL hasIPadProHeight = fabs(height - 1366.f) < DBL_EPSILON; return isIpad && hasIPadProHeight && hasIPadProWidth; } #define UI_IS_LANDSCAPE ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)#define UI_IS_IPAD ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)#define UI_IS_IPHONE ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)#define UI_IS_IPHONE4 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0)#define UI_IS_IPHONE5 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size. Height == 568.0)#define UI_IS_IPHONE6 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size. Height == 667.0)#define UI_IS_IPHONE6PLUS (UI_IS_IPHONE && [[UIScreen mainScreen] bounds]. Size. Height = = 736.0 | | [[UIScreen mainScreen] bounds]. Size. / / to Both width = = 736.0) Orientations# define UI_IS_IOS8_AND_HIGHER ([[UIDevice currentDevice].SystemVersion floatValue] >= 8.0) Wen/Originalee (Jane) the original links: http://www.jianshu.com/p/9d36aa12429f copyright owned by the author, reproduced please contact the author for authorization, and mark "Jane book author".Copy the code
11. Modify the Tabbar Item properties
/ / modify the caption location self. TabBarItem. TitlePositionAdjustment = UIOffsetMake (0, 10); / / modify the self image position. TabBarItem. ImageInsets = UIEdgeInsetsMake (3, 0, 3, 0). / / bulk modify properties for (UIBarItem * item in self. TabBarController. TabBar. Items) {[item setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName: @ "Helvetica" size: 19.0], NSFontAttributeName, nil] forState: UIControlStateNormal]; } // Set selected and unselected font colors [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]]; / / not selected font color [[UITabBarItem appearance] setTitleTextAttributes: @ {NSForegroundColorAttributeName: [UIColor greenColor]} forState:UIControlStateNormal]; / / select the font color [[UITabBarItem appearance] setTitleTextAttributes: @ {NSForegroundColorAttributeName: [UIColor cyanColor]} forState:UIControlStateSelected];Copy the code
12, null-nil-nsnull difference
* nil is an OC, empty object, whose address points to an empty (0) object. Object literal zero * Nil is objective-C class literal zero * NULL is C, empty address, address value is 0, it's a long integer * NSNull is used to solve the problem of adding NULL values to collections like NSArray and NSDictionaryCopy the code
11. Remove the BackBarButtonItem text
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
Copy the code
12. Some reasons why controls cannot interact
1, the control's userInteractionEnabled = NO 2, transparency < 0.01, aplpha 3, when the control is hidden, hidden = YES 4, the position of the child view is out of the valid range of the parent view, the child view cannot interact, set. 5. Views that need to interact are covered by other views (other views enable user interaction).Copy the code
12. Modify the Placeholder text color in UITextField
[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}
Copy the code
13. View lifecycle
Init (initWithNibName) initializes the object and initializes the data. 3. LoadView loads the view from NIB, unless you don't use xiB file to create the view. 5. The viewWillAppear viewWillAppear before the screen, Now this view is going to appear on screen 6, viewDidAppear is rendering on screen 1, viewWillDisappear is going to be removed from screen 2, viewDidDisappear is removed from screen, The dealloc view is destroyed and needs to unload objects that you created in init and viewDidLoad. ViewDidUnload - Called when memory is low and some unneeded views are freed.Copy the code
14. Application lifecycle
1, start but not enter state save: - (BOOL) application: (UIApplication *) application willFinishLaunchingWithOptions (launchOptions NSDictionary *) 2, Basically completed program ready to run: - (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (launchOptions NSDictionary *) 3, When the application is about to enter inactive state execution, the application does not receive messages or events, such as incoming calls: - (void) applicationWillResignActive: (UIApplication *) application 4, when the application in the active state, this is just the opposite with the above method: - (void) applicationDidBecomeActive: (UIApplication *) application 5, when the program is called when pushed to the background. So to set the background to continue, you can set it in this function: - (void) applicationDidEnterBackground: (UIApplication *) application 6, when the program is called from the background will be returned to the front desk, this is just the opposite keep up with the methods below: - (void) applicationWillEnterForeground: (UIApplication *) application 7, when the program will exit is invoked, it is usually used to store data and some cleanup work before: - (void)applicationWillTerminate:(UIApplication *)applicationCopy the code
15. Check whether the view is a child of the specified view
BOOL isView = [textView isDescendantOfView:self.view];
Copy the code
16. Determine whether the object complies with a protocol
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) {
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}
Copy the code
17, the page is forced landscape
#pragma mark - (BOOL)shouldAutorotate{return NO; } - (UIInterfaceOrientationMask supportedInterfaceOrientations) {/ / support which screen direction return UIInterfaceOrientationMaskLandscape; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeRight; } - (BOOL)prefersStatusBarHidden{ return NO; }Copy the code
18. System keyboard notification message
1, 2, UIKeyboardDidShowNotification UIKeyboardWillShowNotification - will pop-up keyboard display keyboard 3, UIKeyboardWillHideNotification will hide the keyboard 4, UIKeyboardDidHideNotification - keyboard has hidden 5, UIKeyboardWillChangeFrameNotification - is going to change the frame 6, UIKeyboardDidChangeFrameNotification - keyboard has changed frameCopy the code
Turn off the navigationController swipe back gesture
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
Copy the code
20. Set the status bar background to any color
- (void)setStatusColor
{
UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
statusBarView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:statusBarView];
}
Copy the code
Get Xcode’s console to support llDB-type printing
Open the terminal and enter three commands: touch ~/.lldbinit echo display @import UIKit >> ~/.lldbinit echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinitCopy the code
Rerun the project the next time and no errors will be reported. 22. Line spacing of Label
- (void) test {NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
// Adjust the line spacing
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0[self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}
Copy the code
23. UIImageView fill mode
UIViewContentModeScaleToFill "@", / / tensile adaptive to fill the whole view @ "UIViewContentModeScaleAspectFit", / / show @ "UIViewContentModeScaleAspectFill" adaptive proportional size, / / original size display @ "UIViewContentModeRedraw." // Redraw @"UIViewContentModeCenter" when size changes, // middle @"UIViewContentModeTop", // top @"UIViewContentModeBottom", // Bottom @"UIViewContentModeLeft", // middle @"UIViewContentModeRight", // middle @"UIViewContentModeTopLeft", / / left @ "UIViewContentModeTopRight", / / upper right @ "UIViewContentModeBottomLeft", / / lower left @ "UIViewContentModeBottomRight", / / the lower rightCopy the code
24. Macro definition detects block availability
#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };
// The usage before the macro definition
if (completionBlock) {
completionBlock(arg1, arg2);
}
// How to use macros after they are defined
BLOCK_EXEC(completionBlock, arg1, arg2);
Copy the code
25, The Debug bar automatically converts Unicode encoding to Chinese characters when printing
// Sometimes when we print Chinese in Xcode, the Unicode code will be printed, and we also need to go to some online sites to convert, with plug-ins much more convenient. DXXcodeConsoleUnicodePlugin plug-inCopy the code
26. Set the status bar text style color
[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
Copy the code
Plug-ins that automatically generate model code
// Esjsonformat-for-xcode can automatically generate model code, saving the time to write model codeCopy the code
27. Some gestures in iOS
Tap gesture (TapGestureRecognizer) swept gently gestures (SwipeGestureRecognizer) long by gestures (LongPressGestureRecognizer) drag (PanGestureRecognizer) Kneading gestures (PinchGestureRecognizer) rotation gestures (RotationGestureRecognizer)Copy the code
27. Some paths related to iOS development
The location of the simulator: / Applications/Xcode. App/Contents/Developer/Platforms/iPhoneSimulator platform/Developer/SDKs document installation location: / Applications/Xcode. App/Contents/Developer/Documentation/DocSets plug-in save the path: ~ / Library/ApplicationSupport/Developer/Shared/Xcode/plug-ins custom code save the path: ~ / Library/Developer/Xcode/UserData/CodeSnippets/if you can't find CodeSnippets folder, can create a new CodeSnippets folder. Certificate path ~ / Library/MobileDevice/Provisioning ProfilesCopy the code
28. The method of obtaining the iOS path
NSString *homeDir = NSHomeDirectory(); The method of access to the Documents directory path NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory NSUserDomainMask, YES). NSString *docDir = [paths objectAtIndex:0]; The method of access to the Documents directory path NSArray * paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory NSUserDomainMask, YES). NSString *cachesDir = [paths objectAtIndex:0]; NSString *tmpDir = NSTemporaryDirectory();Copy the code
**29, string related operations **
Remove all Spaces [STR stringByReplacingOccurrencesOfString: @ "" withString: @" "] to remove fore and aft space [STR stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - (NSString *)uppercaseString; All characters to uppercase letters - (NSString *)lowercaseString All characters to lowercase lettersCopy the code
30, CocoaPods pod install/pod update is slow
Pod install --verbose --no-repo-update pod update --verbose --no-repo-update Pod update --verbose --no-repo-update Adding a parameter can eliminate this step, and speed up quite a bit.Copy the code
31, MRC and ARC mixed setting mode
Targets build Phases > Compile Sources > -fno-objc-arc (-fno-objc-arc); arc (-fno-objc-arc); Targets build Phases > Compile Sources select the file to Compile using ARC double-click -fobjc-arcCopy the code
Change the color of the check box in the cell in the TableView to a different color
_mTableView.tintColor = [UIColor redColor];
Copy the code
Adjust the separaLine line position of TableView
tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
Copy the code
34. Set the NavigationBar to be hidden when sliding
navigationController.hidesBarsOnSwipe = Yes
Copy the code
35, automatic processing of keyboard events, input box occlusion plug-in
IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager
Copy the code
36, Quartz2D correlation
Above and below the figure is a CGContextRef type of data. Graphics context includes: 1, drawing path (various graphics), 2, drawing state (color, line width, style, rotation, scale, pan), 3, output target (where to draw? UIView, picture) 1, gets the current graphics context CGContextRef CTX = UIGraphicsGetCurrentContext (); Add CGContextMoveToPoint(CTX, 20, 20); Render CGContextStrokePath(CTX); CGContextFillPath(ctx); 4, close CGContextClosePath(CTX); CGContextAddRect(CTX, CGRectMake(20, 20, 100, 120)); 6, set line color [[UIColor redColor] setStroke]; CGContextSetLineWidth(CTX, 20); CGContextSetLineCap(CTX, kCGLineCapSquare); 9, set CGContextSetLineJoin(CTX, kCGLineJoinBevel); 10 and circle CGContextAddEllipseInRect (CTX, CGRectMake (30, 50, 100, 100)); 11, specify CGContextAddArc(CTX, 100, 100, 50, 0, M_PI * 2, 1); 12, obtain the image context UIGraphicsGetImageFromCurrentImageContext (); 13, Save graphics context CGContextRestoreGState(CTX)Copy the code
37. Screen shot
/ / 1. Open a graphics context associated with image UIGraphicsBeginImageContextWithOptions (self. View. Bounds. The size, NO, 0.0); / / 2. Get the current graphics context CGContextRef CTX = UIGraphicsGetCurrentContext (); // 3. Get the view layer [self.view.layer renderInContext: CTX]; / / 4. Get photo from the current context UIImage * image = UIGraphicsGetImageFromCurrentImageContext (); / / 5. Close the graphics context UIGraphicsEndImageContext (); / / 6. Save the image to photo album UIImageWriteToSavedPhotosAlbum (image, nil nil, nil);Copy the code
37, left and right dithering animation
CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation]; //2, tells the system what animation to perform. keyAnima.keyPath = @"transform.rotation"; KeyAnima. Values = @ [@ (- M_PI_4/90.0 * 5), @ (M_PI_4/90.0 * 5), @ (- M_PI_4/90.0 * 5)]; / / 3, the execution after not to delete animation keyAnima. RemovedOnCompletion = NO. Keyanima. fillMode = kcafillmodeforward; // 4, save the latest state keyanima. fillMode = kcafillmodeforward; Keyanima. duration = 0.2; // 6, set the number of repeats. keyAnima.repeatCount = MAXFLOAT; // 7, add core animation [self.iconview. layer addAnimation:keyAnima forKey:nil];Copy the code
38. CALayer’s knowledge
The CALayer is responsible for displaying content and animation in the view and THE UIView is responsible for listening to and responding to events and when you create a UIView object, it automatically creates a layer inside the UIView (CALayer) and the UIView itself doesn't display, it's the layer inside it that does display. CALayer attributes: AnchorPoint anchorPoint borderColor borderWidth borderradius cornerRadius shadowColor Opacity opacity offset shadowRadius shadowRadius shadowColor masksToBounds clip-outCopy the code
39, performance related
1. View the reuse, such as UITableViewCell, UICollectionViewCell. 2. Data caching, such as image caching with SDWebImage. 3. Do not block the main thread under any circumstances, and try to put time-consuming operations into child threads. 4. If multiple downloads are concurrent, you can control the number of concurrent downloads. 5. Use lazy loading where appropriate. 6. Reuse significant overhead objects such as NSDateFormatter and NSCalendar. 7. Select an appropriate data store. Avoid circular references. Avoid embellishing the delegate with retain and strong, blocks can cause circular references, NSTimer can cause memory leaks, and so on. 9. When it comes to location, it's best to turn location services off when you're not using them. Because the positioning power consumption, flow. Locking has a significant performance overhead. The interface had better not add too much subViews. 12. 13. Try not to do time-consuming operations in Viewdidload.Copy the code
40, verify your ID number
// check id number - (BOOL)checkIdentityCardNo:(NSString*)cardNo {if (cardNo. Length! = 18) { return NO; } NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil]; NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]]; NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]]; int val; BOOL isNum = [scan scanInt:&val] && [scan isAtEnd]; if (! isNum) { return NO; } int sumValue = 0; for (int i =0; i<17; i++) { sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue]; } NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]]; if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) { return YES; } return NO; }Copy the code
41. The chain order of responders
1> create UIApplication object when the application starts. 2> Then start message loop to listen for all events. 3> When the user touches the screen, "Message loop" listens for this touch event. 4> "message loop" first passes that touch event to UIApplication object. 5> UIApplication object to UIWindow object. 6> UIWindow object to UIWindow's root controller (rootViewController) 7> the controller passes to the view managed by the controller 8> the view managed by the controller searches inside to see which control is in range of the touch point (call Hit test to check if it is in range) 10> "Message loop" knows which button was clicked, and then searches for whether the button has registered the corresponding event. If so, So call this event handler. (Typically, executing the controller's "event handling" method)Copy the code
####42, warning when executing methods using functional Pointers and ignoring performSelector methods
SEL selector = NSSelectorFromString(@"someMethod"); IMP imp = [_controller methodForSelector:selector]; void (*func)(id, SEL) = (void *)imp; func(_controller, selector); SEL selector = NSSelectorFromString(@"processRegion:ofView:"); IMP imp = [_controller methodForSelector:selector]; CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp; CGRect result = func(_controller, selector, someRect, someView); Ignore warnings: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [someController performSelector: NSSelectorFromString(@"someMethod")] #pragma Clang Diagnostic Pop If there are more than one warning to ignore, you can define a macro: #define SuppressPerformSelectorLeakWarning(Stuff) \ do {\ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \ Stuff; Pragma("clang diagnostic POP ") \} while (0) SuppressPerformSelectorLeakWarning( [_target performSelector:_action withObject:self] );Copy the code
43. Simple use of UIApplication
-------- set the marker number -------- // get UIApplication object UIApplication *ap = [UIApplication sharedApplication]; // Before setting up, register a notification, and since ios8, register a notification object first. To be able to receive a reminder. UIUserNotificationSettings *notice = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil]; / / register notification object/ap registerUserNotificationSettings: notice; / / set to remind digital ap applicationIconBadgeNumber = 20; -------- Set the networking status -------- UIApplication * AP = [UIApplication sharedApplication]; ap.networkActivityIndicatorVisible = YES; --------------------------Copy the code
44. UITableView hides white space lines
self.tableView.tableFooterView = [[UIView alloc]init];
Copy the code
GitDiff is a Xcode plug-in that displays git increments
Download address: https://github.com/johnno1962/GitDiff is the name of the plugin GitDiff, role is the ability to display showing a git incremental submit lines of code, such as below to the left of the Xcode identified:Copy the code
46, various collections of web sites
Unicode conversion http://tool.chinaz.com/tools/unicode.aspx JSON string formatting http://www.runoob.com/jsontool RGB color value http://dwz.wailian.work/ http://www.sioe.cn/yingyong/yanse-rgb-16/ short urls generated MAC software download http://www.waitsun.com/ objc China http://objccn.io/Copy the code
47. NSObject inheritance diagram
48. Shallow copy, deep copy, copy, and strong
Shallow copy (changes in either party affect the other) is simply a copy of an object, with several objects sharing a single piece of memory. When memory is destroyed, the Pointers to this piece of memory need to be redefined. Deep copy :(the change of either party does not affect the other party.) the memory address is independently allocated. After the copy is complete, the two objects store the same value but have different memory addresses. The difference between copy and Strong is that copy creates a new object and Strong creates a pointer.Copy the code
49. SEL and IMP
SEL: in fact, it is a kind of packaging of the method. The method is packaged into a SEL type data to find the corresponding method address. After finding the method address, the method can be called. These are run-time features. Sending a message is sending an SEL, then finding the address and calling the method based on the SEL. IMP: is the abbreviation of "implementation", it is objetive -c method (method) implementation code block address, similar to function pointer, through which you can directly access any method. Without the cost of sending a message.Copy the code
50, self and super
In a dynamic method, self stands for "object" and in a static method, self stands for "class" and everything else is the same, just remember this: Self stands for the caller of the current method, self and super are two reserved words provided by OC, but there are fundamental differences. Self is the hidden argument variable of the class, pointing to the object of the current calling method (class is also an object, class object). The other hidden argument is _cmd, which represents the selector of the current class method. Super is not a hidden argument, it's just a "compiler indicator." Super is a smoke screen, a compiler symbol, and it can be replaced with [self class], but the method starts looking for self's superclass.Copy the code
51. Long connection and short connection
Long connection: When there is no data communication, the long connection periodically sends data packets (heartbeat) to maintain the connection status.) Connection → Data transmission → Keep the connection (heartbeat)→ Data transmission → Keep the connection (heartbeat)→...... → Close the connection; Long connection: connect the server to constantly open short connection: (short connection in no data transmission directly closed on the line) connection → data transmission → close connection; Short connection: Connect to the server and disconnect immediately after obtaining data.Copy the code
52. HTTP basic status code
200 OK The request was successful and the desired response header or data body will be returned with this response. 300 Multiple Choices The requested resource has a list of options for feedback, each with its own specific address and browser-driven negotiation information. The user or browser can choose a preferred address for redirection. 400 Bad Request The current Request cannot be understood by the server due to syntax errors. The client should not re-submit this request unless it is modified. 404 Not Found The requested resource failed to be Found on the server. There is no information to tell the user whether the condition is temporary or permanent. If the server is aware of the situation, it should use the 410 status code to tell the old resource that it is permanently unavailable due to some internal configuration mechanism and that there are no reachable addresses. The 404 status code is widely used when the server does not want to reveal exactly why the request was rejected or when no other suitable response is available. 408 Request Timeout The Request times out. The client did not finish sending a request within the time the server was waiting. The client can submit this request again at any time without making any changes. 500 Internal Server Error The Server encountered an unexpected condition that prevented it from processing the request. Typically, this problem occurs when the server's code fails.Copy the code
53, TCP and UDP
TCP: - Establishes a connection to form a channel for transmitting data - Transfers big data over the connection (data size is limited) - Completes the connection through a three-way handshake, is a reliable protocol - Must establish a connection, lower efficiency than UDP UDP: - Just send, don't care to receive - encapsulate data and source and destination into packets, no need to establish a connection - size of each datagram is limited to 64K - unreliable protocol - fastCopy the code
54. Three handshakes and four disconnections
Three handshakes: Are you there - I'm here - LET me ask you something four times disconnect handshake I'm done with this question - are you done - May I go offline - I'm really done bye byeCopy the code
55. The Settings button lights up when pressed
button.showsTouchWhenHighlighted=YES;
Copy the code
56, how to change the color of the Cell tick in tableView to another color?
_mTableView.tintColor = [UIColor redColor];
Copy the code
57. How to adjust the location of Cell separaLine? 六四运动
_myTableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
Copy the code
58. What if the ScrollView somehow doesn’t reach the top of the viewController?
self.automaticallyAdjustsScrollViewInsets = NO;
Copy the code
59, Set TableView not to display empty cells.
self.tableView.tableFooterView = [[UIView alloc]init]
Copy the code
60, copy string to iOS clipboard
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = self.label.text;
Copy the code
61. Macros define multiline methods
Example: #define YKCodingScanData -(void)setValue:(id)value forUndefinedKey:(NSString *)key{} - (instancetype)initWithScanJson:(NSDictionary *)dict{ \ if (self = [super init]) { \ [self setValuesForKeysWithDictionary:dict]; \ } \ return self; \} \Copy the code
62. Remove the cell and the background changes color after clicking
[tableView deselectRowAtIndexPath:indexPath animated:NO]; You can also try this if you find that the present controller is a little slow to pop up in your tableView's didSelectCopy the code
63. Example of thread rent scheduling
// group - Monitors a group of tasks dispatch_group_t group = dispatch_group_create(); dispatch_queue_t q = dispatch_get_global_queue(0, 0); Group monitors tasks. Queue dispatch_group_async(group, q, ^{[NSThread sleepForTimeInterval:1.0]; NSLog(@" task 1 %@", [NSThread currentThread]); }); Dispatch_group_async (group, q, ^{NSLog(@" task 2 %@", [NSThread currentThread]); }); Dispatch_group_async (group, q, ^{NSLog(@" task 3 %@", [NSThread currentThread]); }); When all tasks in the group are completed, "queue scheduling tasks in the block asynchronously!" Dispatch_group_notify (group, dispatch_get_main_queue(), ^{ NSLog(@"OK %@", [NSThread currentThread]); }); NSLog(@"come here");Copy the code
64. View coordinate conversion
ConvertPoint :(CGPoint)point toView:(UIView *)view; // convert pixel point from point view to target view, return the pixel value in target view - (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view; // convert pixel point fromView to current view, return the pixel value in current view - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view; Rect - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view; Rect - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view; // controllerA has a UITableView. The UITableView has multiple rows of UITableVieCell. There is a button on the cell / / in controllerA implementation: CGRect rc = [cell convertRect: cell. The BTN. Frame toView: self. View]; Or CGRect rc = [self view convertRect: cell. The BTN. Frame fromView: cell]; // This rc is the rect of BTN in controllerA or when BTN is known: CGRect rc = [btn.superview convertRect:btn.frame toView:self.view]; Or CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];Copy the code
65, Set animation to end, do not return to the initial state
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
Copy the code
66. UIViewAnimationOptions
Conventional animation attribute set (can choose more than one set at the same time) UIViewAnimationOptionLayoutSubviews: ensure child views to follow in the process of animation movement. UIViewAnimationOptionAllowUserInteraction: allow user interaction in the process of animation. UIViewAnimationOptionBeginFromCurrentState: all views from the current state began to run. UIViewAnimationOptionRepeat: repeat the animation. UIViewAnimationOptionAutoreverse: after running animation to the end point is still in animation way back to the initial point. Set time UIViewAnimationOptionOverrideInheritedDuration: ignore nested animation. UIViewAnimationOptionOverrideInheritedCurve: ignore nested animation speed setting. UIViewAnimationOptionAllowAnimatedContent: redraw the view in the process of animation (note that only applies to ferry animation). UIViewAnimationOptionShowHideTransitionViews: View switch directly to hide old view, according to a new view, rather than remove the old view from the parent view (only applicable to ferry animation) UIViewAnimationOptionOverrideInheritedOptions: don't inherit the parent animation set or animation types. 2. The animation speed control (can be set up from among them to choose a) UIViewAnimationOptionCurveEaseInOut: animation first slowly, then gradually accelerated. UIViewAnimationOptionCurveEaseIn: animation gradually slow down. UIViewAnimationOptionCurveEaseOut: animation gradually accelerated. Uniform execution UIViewAnimationOptionCurveLinear: animation, the default value. 3. Types of transitions (only applicable to ferry animation set, can select a set of fundamental key frame animation, animation does not need to set up) UIViewAnimationOptionTransitionNone: no transitions animation effects. UIViewAnimationOptionTransitionFlipFromLeft: from the left side of the rollover effect. UIViewAnimationOptionTransitionFlipFromRight: from the right side of the rollover effect. UIViewAnimationOptionTransitionCurlUp: flip back animation transition effects. UIViewAnimationOptionTransitionCurlDown: flip forward animation transition effects. UIViewAnimationOptionTransitionCrossDissolve: old view solution shows the effect of a new view. UIViewAnimationOptionTransitionFlipFromTop: flip down from above effect. UIViewAnimationOptionTransitionFlipFromBottom: from the bottom of the reverse effect.Copy the code
67, Get the controller where the current View resides
#import "UIView+ currentcontroller.h "@implementation UIView (CurrentController) /** get the CurrentController */ -(UIViewController *)getCurrentViewController{ UIResponder *next = [self nextResponder]; do { if ([next isKindOfClass:[UIViewController class]]) { return (UIViewController *)next; } next = [next nextResponder]; } while (next ! = nil); return nil; }Copy the code
IOS horizontal scrolling scrollView and system pop gesture return conflict resolution
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { // Pop gestures if first determines whether otherGestureRecognizer system ([otherGestureRecognizer. View IsKindOfClass: NSClassFromString (@ "UILayoutContainerView")]) {/ / and judgment system of gestures is the state began or fail, And judge the position of the scrollView is just on the far left the if (otherGestureRecognizer. State = = UIGestureRecognizerStateBegan && self. The contentOffset. = = x 0) { return YES; } } return NO; }Copy the code
69. Set the status bar direction position
Modify the direction of the status bar, [UIApplication sharedApplication] statusBarOrientation = UIInterfaceOrientationLandscapeLeft; Enumeration value description: Upright UIDeviceOrientationPortraitUpsideDown, / / equipment, home button on the UIDeviceOrientationLandscapeLeft, / / exhaust equipment, The home button on the right UIDeviceOrientationLandscapeRight, / / exhaust equipment, home button in the left UIDeviceOrientationFaceUp, / / equipment flat, Up UIDeviceOrientationFaceDown / / equipment flat screen, the screen down To implement this method for agency - (BOOL) shouldAutorotate {return NO; // Must return no to force manual rotation}Copy the code
69. Modify the spacing between uicollectionViewCells
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(10, 10, 10, 10);
}
Copy the code
70, the timestamp is converted to standard time
-(NSString *)TimeStamp:(NSString *)strTime {// because of the time difference == 28800 SEC NSTimeInterval time=[strTime doubleValue]+28800; NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@" YYYY-MM-DD HH: MM :ss"]; NSString *currentDateStr = [dateFormatter stringFromDate: detaildate]; return currentDateStr; }Copy the code
71. What if I can’t install CocoaPods
Terminal into repos catalog CD ~ /. Cocoapods/repos to create a new folder under the master then download https://coding.net/u/CocoaPods/p/Specs/git to the masterCopy the code
72. Create a Block quickly
Enter: Xcode: inlineBlockCopy the code
Git associated repository, and basic configuration
-------Git global setup------- Git config --global user.name "" Git config --global user. -------Create a new repository------- git clone [email protected]:test/QRZxing.git cd QRZxing touch README.mdgit add README.mdgit commit -m "add README" git push -u origin master -------Existing folder or Git repository------- cd existing_folder git init git remote add origin [email protected]:test/QRZxing.git git add . git commit git push -u origin masterCopy the code
Git Git
75, compiler optimization level GCC_OPTIMIZATION_LEVEL
None: No optimizations With this setting, the compiler's goal is to reduce compilation costs and enable debugging to produce the desired results. Fast: Optimized compilation will take up more time and memory for large functions using this setting, the compiler will try to reduce the size and execution time of the code without any optimization, requiring a lot of compilation time. Faster: The compiler performs almost all supported optimizations, regardless of the balance between space and speed compared to the "Fast" setting, which increases compilation time and the performance of generated code. The compiler does not perform loop unrolling, inline functions, and register variables renaming. Fastest: Enables all optimizations supported by 'Faster', and also allows the inline functions and register variables to be renamed using the Fastest option. Optimize code Size This setting enables "Faster" for all optimizations, generally not increasing code size, and it also performs further optimizations aimed at reducing code size.Copy the code
76. Obtain the local DNS server and obtain the IP address based on the domain name
- (NSString *)outPutDNSServers {res_state res = malloc(sizeof(struct __res_state)); int result = res_ninit(res); NSMutableArray *dnsArray = @[].mutableCopy; if ( result == 0 ) { for ( int i = 0; i < res->nscount; i++ ) { NSString *s = [NSString stringWithUTF8String : inet_ntoa(res->nsaddr_list[i].sin_addr)]; [dnsArray addObject:s]; } } else{ NSLog(@"%@",@" res_init result ! = 0 "); } res_nclose(res); return dnsArray.firstObject; } /// obtain IP address based on domain name - (NSString*)getIPWithHostName:(const NSString*)hostName {const char *hostN= [hostName UTF8String]; Struct hostent *phot; // Record information about the host, including the host name, alias, address type, address length and address list structure. Phot = gethostByName (hostN); @try {// Returns a pointer to the hostent structure that contains the host name and address information corresponding to the given host name. struct in_addr ip_addr; memcpy(&ip_addr, phot->h_addr_list[0], 4); char ip[20] = {0}; inet_ntop(AF_INET, &ip_addr, ip, sizeof(ip)); NSString* strIPAddress = [NSString stringWithUTF8String:ip]; return strIPAddress; } @catch (NSException *exception) { return nil; }}Copy the code
77. Obtain the current wifi connection information
- (void)viewDidLoad {
[super viewDidLoad];
id info = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
NSString *str = info[@"SSID"];
NSString *str2 = info[@"BSSID"];
NSString *str3 = [[ NSString alloc] initWithData:info[@"SSIDDATA"] encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@ %@",str,str2,str3);
}
Copy the code