Reprinted other people's iOS bits and pieces of knowledge

Keywords: Attribute iOS Windows xcode

1. Call code to make APP go into the background and click the Home key. (Private API)

    [[UIApplication sharedApplication] performSelector:@selector(suspend)];

Suspend means: suspend; suspend; suspend; delay;

Second, URL processing with Chinese.

For example, like the following URL, which directly contains Chinese, may not play, then we have to deal with a URL, because he is too fussy, actually in Chinese.

http://static.tripbe.com/videofiles/video/my self-timed video.mp4
NSString *path  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,                                                                                                          (__bridge CFStringRef)model.mp4_url,                                                                         CFSTR(""),                                                                                                    CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

3. Getting the height of UIWebView
Personal most commonly used acquisition method, feel this more reliable

- (void)webViewDidFinishLoad:(UIWebView *)webView  {  
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];  
    CGRect frame = webView.frame;  
    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);  
}  

IV. Setting up pictures for UIView (UILabel applies as well)

  • The first method is:
    Uses UIView to set the background color method, uses the picture to make the pattern color, then passes to the background color.

    UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"];
            UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    [myView setBackGroundColor:bgColor];
    
  • The second method:

    UIImage *image = [UIImage imageNamed:@"yourPicName@2x.png"];
    yourView.layer.contents = (__bridge id)image.CGImage;
    //Set the range of pictures displayed
    yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//The four values are between 0 and 1, corresponding to x, y, width and height.
    

5. Remove the redundant splitting lines of UITableView

yourTableView.tableFooterView = [UIView new];

Sixth, adjust the location of cell division line, two methods are used together to solve the problem of hair loss by violence.

-(void)viewDidLayoutSubviews {

    if ([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.mytableview setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

    }
    if ([self.mytableview respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.mytableview setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }

}

#Pagma mark - cell segmentation line
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

7. UILabel and UIImageView interactive user Interaction Eabled defaults to NO. So if you try to use these two classes as fathers, you can't click on anything in them. There was once a person who asked me to help debug bugs. He debugged for a long time, but he didn't make it. He put the WMPlayer object (player object) on a UI ImageView. So after imageView addSubView:wmPlayer, nothing on the player can be clicked. User Interaction Eabled is set to YES.

8. UISearchController and UISearchBar's Cancel Button Change title Problem, Simple and Rough

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchController.searchBar.showsCancelButton = YES;
    UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"];
    [canceLBtn setTitle:@"cancel" forState:UIControlStateNormal];
    [canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal];
    searchBar.showsCancelButton = YES;
    return YES;
}

9. Why is it so troublesome for UITableView to put away the keyboard?
A property can work well (UIScrollView can also be used)
Did you think [self.view endEditing:YES] before? Very nice, this one is better below.  
yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

Another enumeration, UIScrollViewKeyboard Dismiss Model Interactive, indicates that the keyboard slides inside and the keyboard goes down gradually.

10. NSTimer
1. The time of NSTimer calculation is not accurate.
2. NSTimer needs to be added to the runLoop run to execute, but the runLoop thread must be started.  
3. NSTimer will retain its tagert, and we must stop using intvailte repetitively. If target is self (UIViewController), then VC retainCount+1, if you do not release NSTimer, then your VC will not deal loc, memory leak.

11. UIViewController Unused Size (frame)
Often people in the crowd ask: How to change the size of VC ah?  
Instant silence. Only UIView can set the size. VC is the controller, brother!

12. Get UIColor in hexadecimal (class method or Category can be used, here I use tool class method)

+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;

    //r
    NSString *rString = [cString substringWithRange:range];

    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

13. What day is it today?

+ (NSString *) getweekDayStringWithDate:(NSDate *) date
{
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // Algorithms for Designating Calendars
    NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];

    // 1 is Sunday, 2 is Monday, 3. And so on.

    NSNumber * weekNumber = @([comps weekday]);
    NSInteger weekInt = [weekNumber integerValue];
    NSString *weekDayString = @"(Monday)";
    switch (weekInt) {
        case 1:
        {
            weekDayString = @"(Sunday)";
        }
            break;

        case 2:
        {
            weekDayString = @"(Monday)";
        }
            break;

        case 3:
        {
            weekDayString = @"(Tuesday)";
        }
            break;

        case 4:
        {
            weekDayString = @"(Wednesday)";
        }
            break;

        case 5:
        {
            weekDayString = @"(Thursday)";
        }
            break;

        case 6:
        {
            weekDayString = @"(Friday)";
        }
            break;

        case 7:
        {
            weekDayString = @"(Saturday)";
        }
            break;

        default:
            break;
    }
    return weekDayString;

}

Part of the Round Corner of UIView

UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];
view2.backgroundColor = [UIColor redColor];
[self.view addSubview:view2];

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view2.bounds;
maskLayer.path = maskPath.CGPath;
view2.layer.mask = maskLayer;
//Among them,
byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
//The corners that need to be rounded are specified. This parameter is of UIRectCorner type, and the optional values are:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners

It's easy to see what the name means, just use "|" to combine.

15. Hide Navigation Bar when setting sliding

navigationController.hidesBarsOnSwipe = Yes;

16. iOS draws dotted lines
Remember to import the QuartzCore framework first

#import <QuartzCore/QuartzCore.h>

CGContextRef context =UIGraphicsGetCurrentContext();  
CGContextBeginPath(context);  
CGContextSetLineWidth(context, 2.0);  
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);  
CGFloat lengths[] = {10,10};  
CGContextSetLineDash(context, 0, lengths,2);  
CGContextMoveToPoint(context, 10.0, 20.0);  
CGContextAddLineToPoint(context, 310.0,20.0);  
CGContextStrokePath(context);  
CGContextClosePath(context);  

17. The preferred MaxLayoutWidth property of the multi-line UILabel in the automatic layout is needed to display the multi-line content normally. In addition, if incomplete text appears, it can be calculated on the basis of + 0.5.

    CGFloat h = [model.message boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;

18. Prohibiting the automatic lock screen when the program is running
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

19. KVC is related and supports operators.
KVC also provides very complex functions, mainly the following.
(1) Simple set operators
There are five simple set operators @avg, @count, @max, @min, @sum, which means that there is no need for me to say anything about them. Customization is not yet supported.

@interface Book : NSObject
@property (nonatomic,copy)  NSString* name;
@property (nonatomic,assign)  CGFloat price;
@end
@implementation Book
@end


Book *book1 = [Book new];
book1.name = @"The Great Gastby";
book1.price = 22;
Book *book2 = [Book new];
book2.name = @"Time History";
book2.price = 12;
Book *book3 = [Book new];
book3.name = @"Wrong Hole";
book3.price = 111;

Book *book4 = [Book new];
book4.name = @"Wrong Hole";
book4.price = 111;

NSArray* arrBooks = @[book1,book2,book3,book4];
NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];
NSLog(@"sum:%f",sum.floatValue);
NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];
NSLog(@"avg:%f",avg.floatValue);
NSNumber* count = [arrBooks valueForKeyPath:@"@count"];
NSLog(@"count:%f",count.floatValue);
NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];
NSLog(@"min:%f",min.floatValue);
NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];
NSLog(@"max:%f",max.floatValue);

//Print results
2016-04-20 16:45:54.696 KVCDemo[1484:127089] sum:256.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000

NSArray Quickly Finds the Maximum, Minimum and Mean Values

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);

20. When using MBProgressHud, try not to add it to UI Windows, just add self.view. If you add UI Windows to the iPad, MBProgressHud will not rotate when you rotate the screen. Someone had encountered this bug before, so I asked him to change it to self.view to solve the bug.

21. Force App to exit directly (no flip, no crash)

    - (void)exitApplication {
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        [UIView animateWithDuration:1.0f animations:^{
            window.alpha = 0;
        } completion:^(BOOL finished) {
            exit(0);
        }];
    }

22. Label row spacing

 NSMutableAttributedString *attributedString =    
   [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
    NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];  
   [paragraphStyle setLineSpacing:3];

    //Adjust row spacing 
   [attributedString addAttribute:NSParagraphStyleAttributeName 
                         value:paragraphStyle 
                         range:NSMakeRange(0, [self.contentLabel.text length])];
     self.contentLabel.attributedText = attributedString;

23. The slow update of Cocoa Pods pod install/pod update
pod install –verbose –no-repo-update  
pod update –verbose –no-repo-update 
If no later parameters are added, the spec repository of CocoaPods will be upgraded by default. Adding one parameter can omit this step, and then the speed will increase a lot.

MRC and ARC Mixed Editing Settings
Select files that do not require arc compilation under Compile Sources under the build phases option of targets in XCode
Double-click input-fno-objc-arc.
ARC classes can also be used in MRC projects by the following methods:
Select the files to be compiled using arc under Compile Sources under the build phases option of targets in XCode
Double-click input-fobjc-arc

25. Change the color of the cell check in the tableview to another color.
_yourTableView.tintColor = [UIColor redColor];

26. Solve the problem of pressing two buttons into two view s at the same time.
[button setExclusiveTouch:YES];

Twenty-seven. Modify the font color and size of textFieldplaceholder

textField.placeholder = @"enter one user name";  
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

28. Prohibit the copy and paste menu of textField and textView

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
     if ([UIMenuController sharedMenuController]) {
       [UIMenuController sharedMenuController].menuVisible = NO;
     }
     return NO;
}

Twenty-nine: How to access the app store page of my software
First use iTunes Link Maker to find the software's access address in itms-apps://ax.itunes.apple.com/... And then

#define  ITUNESLINK   @"itms-apps://ax.itunes.apple.com/..."
NSURL *url = [NSURL URLWithString:ITUNESLINK];
if([[UIApplication sharedApplication] canOpenURL:url]){
     [[UIApplication sharedApplication] openURL:url];
}

If you change itms-apps to http in the above address, you can open it in the browser. You can put this address on your website and link to app store.  
iTunes Link Maker address: http://itunes.apple.com/linkmaker

Level 30 and Level 2 Page Hiding System tabbar
1. Single processing

YourViewController *yourVC = [YourViewController new];
yourVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:yourVC animated:YES];

2. Unify in the base class.
Create a new class BaseNavigation Controller to inherit UINavigation Controller, and then rewrite the method - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated. All push events follow this approach.

@interface BaseNavigationController : UINavigationController

@end
    -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
        [super pushViewController:viewController animated:animated];
        if (self.viewControllers.count>1) {
            viewController.hidesBottomBarWhenPushed = YES;
        }
    }

31. Return gesture of canceling system

   self.navigationController.interactivePopGestureRecognizer.enabled = NO;

Thirty-two. Modify font size and color in UIWebView

1. UIWebView sets font size, color, font:
UIWebView can't set some attributes of fonts by its own attributes. It can only be set by html code.
After the webView is loaded, the

- (void)webViewDidFinishLoad:(UIWebView *)webView Method additions js Code  
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'";  
    [_webView stringByEvaluatingJavaScriptFromString:str]; 

Or add the following code

NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor];   
        [webView stringByEvaluatingJavaScriptFromString:jsString];   

Thirty-three. NSString Processing Skills
Use scenarios for example: Can be used to process user input text in UITextField

//String to be processed
NSString *string = @" A B  CD   EFG\n MN\n";

//String 1= @ "ABCDEF nMN\ n" is replaced by string.
NSString *string1 = [string stringByReplacingOccurrencesOfString:@" " withString:@""];

//String 2=@ "A B CD EFGn MN\n" after removing the space at both ends.
NSString *string2 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

//Remove return at both ends (note both ends), string3=@ "A B CD EFG n MN" after treatment;
NSString *string3 = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

//String 4= @ "A B CD EFG\n MN" after removing the blanks at both ends and returning (note both ends);
NSString *string4 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Thirty-four. The main thread operates the UI (updating the UI can only be done on the main thread)
Interpretation: The so-called updating UI and operating UI in the main thread roughly means setting the text of UILabel or badgeValue of tabbar, image of UIImageView and so on.

Back to the main thread mode 1:

[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];

The performance Selector OnMainThread method is the classification method of NSObject. Each NSObject object has this method.
The selector method it calls is the current method of invoking the control, such as the method of UIImageView when it is invoked using UIImageView.
Object: A parameter representing the calling method, but only one parameter can be passed (encapsulate with an object if there are more than one parameter)
waitUntilDone: Whether Thread Tasks Complete Execution

Back to the main thread mode 2:

dispatch_async(dispatch_get_main_queue(), ^{
        //Code to update UI
    });

This little explanation, GCD method, be careful not to use in the main thread.

Judgment Simulator

if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"Simulator.");
    }else{
        NSLog(@"Not an emulator");
    }

36. Real machine test report TCWeiboSDK 93 duplicate symbols for architecture armv7

This is because two identical class libraries were introduced in the project, and two different instruction sets were introduced in my project.

37. AFnet Working "Request failed: unacceptable content-type: text/html" error

AFURLResponseSerialization.m File Settings

self.acceptableContentTypes = [NSSetsetWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];

Plus @"text/html", the part is actually to add a data format returned by the server.

38. Hide the return button after navigation jump

//Hide the left side of the head to return
self.navigationItem.hidesBackButton=YES;

39. Two ways to delete all records of NSUserDefaults

//Method 1
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

//Method two
- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

UITableView Sets Section Spacing
When using UITableView StyleGrouped type UITableView, it is often strange to see redundant section spacing, which may be because you only set one of the footer or header spacing, and the other defaults to 20 heights, which can be solved by setting a floating point number returning 0.001 CGFlot.

//Header Bottom Spacing
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section  
{  
    return 40;//section Head Height
}  

//footer bottom spacing
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section  
{  
    return 0.001;  
}  

NSLog Output Format Set

%@ Object
 :% d,% I. Integers
 % u 
(f) Floating point/double word
 *% x,% X binary integers
 *% o) octal integers
• %zu     size_t
 Percentage p pointer
 (e) Floating Point/Double Word (Scientific Computing)
(g) Floating point/double word
  s  C String ___________
* s Pascal string
 Character% c ____________
• %C       unichar
 *% lld * 64-bit long integer (long long long)
*% llu * Inconsistent 64-bit long integers
 % Lf. 64-bit double word

Summary of Common GCD

In order to use GCD conveniently, Apple has provided some methods for us to put block s in the main thread or background thread, or delay execution. Examples used are as follows:

    // Background implementation: 
     dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
          // something 
     }); 
     // Main thread execution: 
     dispatch_async(dispatch_get_main_queue(), ^{ 
          // something 
     }); 
     // One-time execution: 
     static dispatch_once_t onceToken; 
     dispatch_once(&onceToken, ^{ 
         // code to be executed once 
     }); 
     // Delay 2 seconds execution: 
     double delayInSeconds = 2.0; 
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
         // code to be executed on the main queue after delay 
     }); 

dispatch_queue_t can also be defined by itself. To customize queue, you can use the dispatch_queue_create method as follows:

    dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL); 
    dispatch_async(urls_queue, ^{ 
         // your code 
    }); 
    dispatch_release(urls_queue); 

In addition, GCD has some advanced uses, such as allowing two threads in the background to execute in parallel, and then waiting for the two threads to finish, then summarizing the execution results. This can be achieved by dispatch_group, dispatch_group_async and dispatch_group_notify. Examples are as follows:

    dispatch_group_t group = dispatch_group_create(); 
    dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ 
          // Thread 1 for parallel execution 
     }); 
     dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ 
          // Thread 2 for parallel execution 
     }); 
     dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{ 
          // When the above thread is finished, the last block is notified to ensure the final execution of this part of the code. 
     }); 

43. Random Numbers in iOS

Generate random positive integers between 0-x

int value =arc4random_uniform(x + 1);

Generating random positive integers

int value = arc4random() 

The code for obtaining integers between 0 and x-1 by arc4random() is as follows:

int value = arc4random() % x; 

The code for getting integers between 1 and x is as follows:

int value = (arc4random() % x) + 1; 

Finally, if you want to generate a floating point number, you can define the following macros in the project:

#define ARC4RANDOM_MAX      0x100000000 

Then you can use arc4random() to get floating-point numbers between 0 and 100 (twice the accuracy of rand ()) with the following code:

double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);

UITableViewCell comes with the system, where cell.accessoryView can customize controls

 if (indexPath.section == 2 && indexPath.row == 0) {
        cell.accessoryView = [[UISwitch alloc] init];
    } else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

IsKindOfClass, usage distinction of isMemberOfClass

- (BOOL) isKindOfClass: classObj determines whether it is an instance of this class or a subclass of this class?
- (BOOL) isMemberOfClass: classObj determines whether it is an instance of this class?

Example 1:

   Person *person = [[Person alloc] init];      //Parent class
   Teacher *teacher = [[Teacher alloc] init];  //Subclass

   //YES   
   if ([teacher isMemberOfClass:[Teacher class]]) {  
        NSLog(@"teacher Teacher Class members");  
   }  
   //NO   
   if ([teacher isMemberOfClass:[Person class]]) {  
       NSLog(@"teacher Person Class members");  
   }  
   //NO   
   if ([teacher isMemberOfClass:[NSObject class]]) {  
       NSLog(@"teacher NSObject Class members");  
   }  

Example two:

Person *person = [[Person alloc] init];  
Teacher *teacher = [[Teacher alloc] init];  

//YES   
if ([teacher isKindOfClass:[Teacher class]]) {  
    NSLog(@"teacher yes Teacher Class or Teacher Subclasses");  
}  
//YES   
if ([teacher isKindOfClass:[Person class]]) {  
    NSLog(@"teacher yes Person Class or Person Subclasses");  
}  
//YES   
if ([teacher isKindOfClass:[NSObject class]]) {  
    NSLog(@"teacher yes NSObject Class or NSObject Subclasses");  
}  

IsMemberOfClass judges whether it belongs to such instances and whether it has anything to do with the parent class, so isMemberOfClass will not be NO until it refers to the parent class.

About UIScreen

The UIScreen object contains the entire screen's boundary rectangle. When constructing an application's user interface, you should use the properties of the object to get the recommended rectangular size to construct your application window.

CG Rect bound = [[UIScreen mainScreen] bounds]; // Returns a Ret with a status bar
CG Rect frame = [[UIScreen mainScreen] application frame]; // Returns a Ret without a status bar
float scale = [[UIScreen mainScreen] scale]; // Get the device's natural resolution

Further explanation is needed for the scale attribute:

In the past, the screen resolution of the iphone device was 320 * 480. Later, apple adopted the display technology called Retina in the iPhone 4, and the display screen of 960 x 640 pixel resolution in the iPhone 4. Because the screen size remains unchanged, or 3.5 inches, the increase in resolution increases the display resolution of the iPhone 4 to four times that of the iPhone 3GS, with 326 pixels per inch.

The scale attribute has two values:
scale = 1; when it represents the resolution of 320 * 480 for the current device (the device before the iPhone 4)
scale = 2; when the resolution is 640*960

// Determine screen type, normal or retina
    float scale = [[UIScreen mainScreen] scale];  
    if (scale == 1) {  
        bIsRetina = NO;  
        NSLog(@"Plain screen");  
    }else if (scale == 2) {  
        bIsRetina = YES;  
        NSLog(@"Retinal screen");  
    }else{  
        NSLog(@"unknow screen mode !");  
    } 

Forty-seven. The clipsTobounds attribute of UIView

View2 adds view1 to it. If view2 is larger than view1, or the coordinates of view2 are not all within the scope of view1, view2 is covered by view1, meaning that the excess parts will be drawn. UIView has an attribute, clipsTobounds defaults to NO. If we want view2 to make that part out of reality, we have to change its parent view, which is also the clipsTobounds attribute value of view1. view1.clipsTobounds = YES;
It can solve the problem of coverage well.

48. Interchange between Baidu coordinates and Mars coordinates

//Baidu to Mars coordinates
+ (CLLocationCoordinate2D )bdToGGEncrypt:(CLLocationCoordinate2D)coord
{
    double x = coord.longitude - 0.0065, y = coord.latitude - 0.006;
    double z = sqrt(x * x + y * y) - 0.00002 * sin(y * M_PI);
    double theta = atan2(y, x) - 0.000003 * cos(x * M_PI);
    CLLocationCoordinate2D transformLocation ;
    transformLocation.longitude = z * cos(theta);
    transformLocation.latitude = z * sin(theta);
    return transformLocation;
}

//Mars coordinates to Baidu coordinates
+ (CLLocationCoordinate2D )ggToBDEncrypt:(CLLocationCoordinate2D)coord
{
    double x = coord.longitude, y = coord.latitude;

    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * M_PI);
    double theta = atan2(y, x) + 0.000003 * cos(x * M_PI);

    CLLocationCoordinate2D transformLocation ;
    transformLocation.longitude = z * cos(theta) + 0.0065;
    transformLocation.latitude = z * sin(theta) + 0.006;

    return transformLocation;
}

49. Draw a line of 1 pixel

#define SINGLE_LINE_WIDTH           (1 / [UIScreen mainScreen].scale)
#define SINGLE_LINE_ADJUST_OFFSET   ((1 / [UIScreen mainScreen].scale) / 2)

The code is as follows:

UIView *view = [[UIView alloc] initWithFrame:CGrect(x - SINGLE_LINE_ADJUST_OFFSET, 0, SINGLE_LINE_WIDTH, 100)];

Note: If the line width is even Point, do not set the offset, otherwise the line will be distorted.

UILabel Displays HTML Text (IOS7 or more)

NSString * htmlString = @"<html><body> Some html string \n <font size=\"13\" color=\"red\">This is some text!</font> </body></html>";
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
    myLabel.attributedText = attrStr;
    [self.view addSubview:myLabel];

51. Step of adding pch file

1: Create a new file IOS - > other - > PCH file and create a PCH file: "Project name - Prefix.pch":
2: Add the path of the precompile header option in building setting s to "$(SRCROOT)/project name/pch file name" (e.g. $(SRCROOT)/LotteryFive/LotteryFive-Prefix.pch)
3: Using Precompile Prefix Header as YES, pre-compiled pch files will be cached to improve compilation speed.

52. Compatible font size 6 plus differs from the following

#define FONT_COMPATIBLE_SCREEN_OFFSET(_fontSize_)  [UIFont systemFontOfSize:(_fontSize_ *([UIScreen mainScreen].scale) / 2)]
In the iPhone 4-6, the scaling factor scale=2; in the iPhone 6 +, the scaling factor scale=3

When used:

myLabel.font=FONT_COMPATIBLE_SCREEN_OFFSET(15);

Fifty-three. APP Virtual Machine can run. This problem occurs during real-time debugging because the project name is set to Chinese.

App installation failed 
There was an internal API error. 
Packaging Product Name in Build Settings is set to Chinese

On Masonry

a:make.equalTo or make.greaterThanOrEqualTo (At most) or make.lessThanOrEqualTo(At least)

make.left.greaterThanOrEqualTo(label);
make.left.greaterThanOrEqualTo(label.mas_left);

//width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(@200);
make.width.lessThanOrEqualTo(@400)
b: masequalTo and equalTo Difference: masequalTo than equalTo There are many type conversion operations. Generally speaking, the two methods are common in most cases, but they are used for numeric elements. mas_equalTo. For objects or multiple attributes, use equalTo. Especially when you have multiple attributes, you must use equalTo

c: Some simple assignments

// make top = superview.top + 5, left = superview.left + 10,
// bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))

// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel)

// make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))

// make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))

d:and Application of keywords

make.left.right.and.bottom.equalTo(superview); 
make.top.equalTo(otherView);
e:Priority(.priority,.priorityHigh,.priorityMedium,.priorityLow)

.priority Allow you to specify an exact priority
.priorityHigh Equivalent to UILayoutPriorityDefaultHigh
.priorityMedium Between high and low
.priorityLow Equivalent to UILayoutPriorityDefaultLow

//Example:
make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();
make.top.equalTo(label.mas_top).with.priority(600);
g:Use mas_makeConstraints Establish constraint Later, you can use local variables or attributes to save it for reference next time; if you create more than one constraints,You can use arrays to save them.

// Local or global
@property (nonatomic, strong) MASConstraint *topConstraint;

// Create constraints and assign values
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top);
    make.left.equalTo(superview.mas_left).with.offset(padding.left);
}];

// Later you can access self.topConstraint directly
[self.topConstraint uninstall];

h:mas_updateConstraints Update constraints, sometimes you need to update constraint(For example, animation and debugging)Instead of creating fixtures constraint,have access to mas_updateConstraints Method


- (void)updateConstraints {
    [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(self.buttonSize.width)).priorityLow();
        make.height.equalTo(@(self.buttonSize.height)).priorityLow();
        make.width.lessThanOrEqualTo(self);
        make.height.lessThanOrEqualTo(self);
    }];

    //Call parent updateConstraints
    [super updateConstraints];
}

i:mas_remakeConstraints Update constraints, mas_remakeConstraints and mas_updateConstraints Similar, all updates constraint. However, mas_remakeConstraints Before deletion constraint,Then add a new one. constraint(Applicable to mobile animation);and mas_updateConstraints Just update constraint The value.


- (void)changeButtonPosition {
    [self.button mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(self.buttonSize);

        if (topLeft) {
       make.top.and.left.offset(10);
        } else {
       make.bottom.and.right.offset(-10);
        }
    }];
}

round/roundf/ceil/ceilf/floor/floorf in iOS

round: If the parameter is a decimal, rounding itself.  
ceil: If the parameter is decimal, find the smallest integer but not less than itself.
floor: If the parameter is decimal, find the largest integer but not greater than itself.

Example: If the value is 3.4, then
3.4 – round 3.000000 
– ceil 4.000000 
– floor 3.00000

56. The Chinese input method has the function of association and recommendation on the keyboard, so it may cause the length of the text content to be somewhat unexpected and lead to cross-border.

* Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds' 
The processing is as follows (textView. markedTextRange = nil)

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.text.length >= self.textLengthLimit && text.length > range.length) {
        return NO;
    }

    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.placeholder.hidden = (self.textView.text.length > 0);

    if (textView.markedTextRange == nil && self.textLengthLimit > 0 && self.text.length > self.textLengthLimit) {
        textView.text = [textView.text substringToIndex:self.textLengthLimit];
    }
}

Setting up Transparency of Navigation Bar and Starting Position of Top Layout

Attribute: translucent

Close

self.navigationController.navigationBar.translucent = NO;

open

self.navigationController.navigationBar.translucent = YES;

Attribute: Automatically AdjustsScrollViewInsets

When Automatically AdjustsScrollViewInsets is NO, the tableview starts at the top of the screen, which is covered by the navigational bar-status bar.

When Automatically AdjustsScrollViewInsets is YES, it is also the default behavior

58. UIScrollView offset 64

If the first control in a VC is UIScrollView, notice that the first control is addsubview on VC.view. The View added to the scrollView then shifts 64 at point Y (that is, the height of the navigationBar is 44 + the height of the battery bar is 20).  
This won't happen until iOS 7.

Solutions:
Self.automatic AdjustsScrollViewInsets = false; self is your current VC.

If this scrollView is not the first to be added to self.view. No 64 offset will occur.

UIWebView Black Edge Solution at the Bottom of IOS9

The black bar at the bottom of UIWebView is ugly (it won't appear under IOS8, it will appear in IOS9). Especially when there are transparent controls at the bottom, the hiding method is very simple. Just set opaque to NO and background color to clearColor.

60. tabBarController jumps to another level 1 page

When we use tabBarController, if we have already reached one of the subpages of TabBar and want to jump to a certain level of page, if we write like this, the bottom appears black edge, causing the bug that tabbar disappears.

[self.navigationController popToRootViewControllerAnimated:YES];

((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;

Solution 1: Delete animation

 [self.navigationController popToRootViewControllerAnimated:NO];

((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;

Solution 2: Delay execution of another system operation

 [self.navigationController popToRootViewControllerAnimated:NO];

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;

    });

61. UIWebView Gets Html title Title

titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

62. Conversion of Chinese Characters into Pinyin

- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst
{
    //Converted to a variable string
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //Convert to phonetic alphabet with tone first
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //Converting to Untoned Pinyin
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str capitalizedString];
    //Conversion to capital Pinyin
    if(isGetFirst)
    {
        //Gets and returns the initials
        return [pinYin substringToIndex:1];
    }
    else
    {
        return pinYin;
    }
}

63. Attribute Name Solution Starting with new
Because new is the OC keyword, there is also alloc.
@property (nonatomic,copy) NSString *new_Passwd; 

Writing like this will cause errors and can be replaced by

@property (nonatomic,copy,getter = theNewPasswd) NSString *new_Passwd;

64. Remove compiler warnings

a: Method Abandonment Warning

#pragma clang diagnostic push  

#pragma clang diagnostic ignored "-Wdeprecated-declarations"      
//Alarm methods, such as SEL 
[TestFlight setDeviceIdentifier:[[UIDevice currentDevice] uniqueIdentifier]];  

#pragma clang diagnostic pop  

b: Unused variables

#pragma clang diagnostic push   
#pragma clang diagnostic ignored "-Wunused-variable"   

int a;   

#pragma clang diagnostic pop 

65. Self. Navigation Controller. ViewControllers Modification
Mainly solve those disorderly jump logic, not in order to solve the problem;

var controllerArr = self.navigationController?.viewControllers// Get the Controller array
 ContrllerArr?. removeAll ()// Remove the saved historical path in ContrllerArr
 // Add a new path
controllerArr?.append(self.navigationController?.viewControllers[0])
controllerArr?.append(C)
controllerArr?.append(B)
 // At this point, the historical path is (root-> c-> b)
 // set the new jump path into self.navigationController
self.navigationController?.setViewControllers(controllerArr!, animated: true)
// Write directly, complete the jump B page while modifying the previous jump path

Posted by batfink on Fri, 22 Mar 2019 17:45:52 -0700