Years of experience in iOS development (1)

Summed up a few months of things, and finally to share with you, not to mention, look directly at things!

1, prohibit cell phone sleep

[UIApplication sharedApplication].idleTimerDisabled = YES;

2, hide a line cell

- (CGFloat) tableView: (UITableView * tableView) heightForRowAtIndexPath: (NSIndexPath * indexPath) {/ / if you need a line that is hidden, return to the height of 0 if (indexPath.row = = YouWantToHideRow) return 0; return 44;} / / then you need to hide the cell when calling [self.tableView beginUpdates]; [self.tableView endUpdates];

3, disable button highlighting

Button.adjustsImageWhenHighlighted = NO; or at the time of creation UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

4, tableview encountered this error, failed, to, obtain, a, cell, from, dataSource, its

It’s because your cell was called early. The cell is first recycled, and then cell is created. Wrong order
possible reasons: 1, Xib cell has not registered the cell 2, in memory cache (i.e. find through your cellId cell is not the type you want), at this time need to change the cell logo

5, cocoa, pods reported this error: unable to access’’: Operation timed out after 0 milliseconds with 0 out of 0 bytes received

The solution: it may be a network problem, the network request is timed out, and you just have to try again

6, cocoa, pods, ERROR:, While, executing, gem… (Errno:: EPERM)

The solution:

7, animation switch window root controller

Options is [UIView transitionWithView:[UIApplication / sharedApplication].keyWindow duration:0.5f options:UIViewAnimationOptionTransitionCrossDissolve animation options animations:^{BOOL oldState = [UIView areAnimationsEnabled]; [UIView setAnimationsEnabled: NO]; [UIApplication sharedApplication].keyWindow.rootViewController = [RootViewController new]; [UIView setAnimationsEnabled:oldState];} completion:^ (BOOL finished) {}];

8. Removing duplicate objects from an array

NSArray *newArr = [oldArr valueForKeyPath:@ "@distinctUnionOfObjects.self" [];

9, compile time encountered no, such, file, or, directory: / users / apple / XXX

Because the compile time, this path can not find the file, to solve this problem, the first is to check the missing file is not in the project, if not in the project, need to drag from the local, if it already exists in the project, or drag is also wrong, this time need to search the file build phases, this time is likely to search two of the same document, at this time, there is a path is correct, you can delete another. If you delete or not, you need to delete the two, and then re – project into the document can be dragged

Years of experience in iOS development (1)
build phases

In 10, iOS8 systems, tableView is best implemented under the -tableView: heightForRowAtIndexPath: proxy method, otherwise in iOS8 may appear incomplete or unable to respond to events

11, iOS8 in the realization of sideslip function, this method must be achieved, otherwise in iOS8 can not sideslip

/ / method must be written, and editActionsForRowAtIndexPath used inside, what also don't write - (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath * indexPath) {}

12, three notice

NSSystemTimeZoneDidChangeNotification monitor the modification time of two button interface state change
UIApplicationSignificantTimeChangeNotification to monitor user change time (just click on the settings button will automatically call) NSSystemClockDidChangeNotification to monitor user modification time (time different calls)

13, SDWebImage local cache can sometimes harm people. If the cache before a picture, even if the next server for this picture, but the picture did not change URL, use sdwebimage to download or before that, I encountered this problem, don’t go to your server, empty cache is good again.

14, before the line, pay attention to:

test code all the deleted code 2), if the audit mode background, remind the background open
3), the main process to run
4 Waring), the global search, check all labeled Waring place

15, jump into the app permissions settings

App set if (UIApplicationOpenSettingsURLString / jump! = NULL) {NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; [[UIApplication sharedApplication] openURL:url];}}

16, give a screenshot of view

UIGraphicsBeginImageContextWithOptions (view.bounds.size, YES, 0); [view.layer (renderInContext:UIGraphicsGetCurrentContext)]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext (UIGraphicsEndImageContext ());

17, if you want to dynamically modify the tableView tableHeaderView or tableFooterView height, you need to reset the tableView, rather than directly change the height. The correct thing is to reset the tableView.tableFooterView = change the height of the view. Why? In fact, more than iOS8 direct change height is no problem, in the iOS8 appeared in the contentSize inaccurate problem, this is the solution.

18, when the object is called nil, the method of calling this object classification will not execute

19, collectionView content is less than its width and height, can not scroll, settings can scroll:

CollectionView.alwaysBounceHorizontal = YES; collectionView.alwaysBounceVertical = YES;

20, set the title color and size on the navigationBar

[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor, youColor], NSFontAttributeName: [UIFont systemFontOfSize:15]}]

21, color transfer picture

+ (UIImage *) cl_imageWithColor: (UIColor * color) {CGRect rect = CGRectMake (0.0F, 0.0F, 1.0F, 1.0F); UIGraphicsBeginImageContext (rect.size); CGContextRef (context = UIGraphicsGetCurrentContext); CGContextSetFillColorWithColor (context, [color CGColor]); CGContextFillRect (context, rect); UIImage (*image = UIGraphicsGetImageFromCurrentImageContext); (UIGraphicsEndImageContext); return image;}

22, view set fillet

#define ViewBorderRadius (View, Radius, Width, Color) / [View.layer / setCornerRadius: (Radius)]; [View.layer / setMasksToBounds:YES]; [View.layer / setBorderWidth: (Width)]; setBorderColor:[Color / [View.layer CGColor]] / / view fillet

23, strong / weak reference

#define WeakSelf (type) __weak typeof (type) weak##type = type; / / weak #define StrongSelf (type) __strong typeof (type) type = weak##type; / / strong

24, radian converted by angle

#define DegreesToRadian (x) (M_PI * (x) / 180)

25, by radian conversion angle

#define RadianToDegrees (radian) (radian*180.0) / (M_PI)

26, access to picture resources

#define GetImage (imageName) [UIImage imageNamed:[NSString stringWithFormat:@ imageName]] "% @".

27, get temp

#define, PathTemp, NSTemporaryDirectory ()

28, get sandbox Document

#define, PathDocument, [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

29, get sandbox Cache

#define, PathCache, [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject]

30, the GCD code is executed only once

#define, kDISPATCH_ONCE_BLOCK (onceBlock), static, dispatch_once_t, onceToken, dispatch_once (&, onceToken, onceBlock);

31, custom NSLog

#ifdef, DEBUG, #define, NSLog (FMT,...), NSLog ((@%s, [Line,%d], FMT), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #else, #define, NSLog (...), #endif

32, Font

#define FontL (s) [UIFont systemFontOfSize:s weight:UIFontWeightLight] #define FontR (s) [UIFont systemFontOfSize:s weight:UIFontWeightRegular] #define FontB (s) [UIFont systemFontOfSize:s weight:UIFontWeightBold] #define FontT (s) [UIFont systemFontOfSize:s weight:UIFontWeightThin] #define Font (s) FontL (s)


#define FORMAT (F, [NSString, stringWithFormat:f, __VA_ARGS__] ##...)

34, run on the main thread

#define, kDISPATCH_MAIN_THREAD (mainQueueBlock), dispatch_async (dispatch_get_main_queue (), mainQueueBlock);

35, open asynchronous threads

#define, kDISPATCH_GLOBAL_QUEUE_DEFAULT (globalQueueBlock), dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

36, notice

#define NOTIF_ADD (n, f) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (f) name:n object:nil] #define NOTIF_POST (n, O) [[NSNotificationCenter defaultCenter] postNotificationName:n object:o] #define NOTIF_REMV ([[NSNotificationCenter defaultCenter] removeObserver:self])

37, random colors

+ (UIColor * RandomColor) {NSInteger aRedValue = arc4random (aGreenValue = NSInteger)% 255; arc4random (aBlueValue = NSInteger)% 255; arc4random (255)%; *randColor = UIColor [UIColor colorWithRed:aRedValue / 255.0f green: aGreenValue / 255.0f blue:aBlueValue / 255.0f alpha:1.0f]; return randColor;}

38, get window

(UIWindow* + getWindow) {UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow; for (ID item in [UIApplication sharedApplication].windows if ([item) {class] [UIWindow = = class]) {if (! ((UIWindow*) item).Hidden) {win = item; break;}}} return win;}

39, modify the font color, size of textField placeholder

[textField, setValue:[UIColor, redColor], forKeyPath:@, "_placeholderLabel.textColor"]; [textField, setValue:[UIFont, boldSystemFontOfSize:16], forKeyPath:@, "_placeholderLabel.font"];

40, unified keyboard

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

41. Control the screen rotation and write in the controller

Whether to support the automatic transfer screen / * * * / - (BOOL) shouldAutorotate {return YES;} / * * * / - which support the direction of the screen (UIInterfaceOrientationMask supportedInterfaceOrientations) {return UIInterfaceOrientationMaskLandscapeLeft UIInterfaceOrientationMaskLandscapeRight} / * * |; the direction of the screen (the current default ViewController must be out of the UIViewController (by modal modal invalid navigation way) calls. This method) * / - (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation return UIInterfaceOrientationLandscapeLeft | {UIInterfaceOrientationLandscapeRight};

42, get the app cache size

- (CGFloat) getCachSize imageCacheSize sharedImageCache] getSize] {NSUInteger = [[SDImageCache; / / / / get a custom cache size with the enumerator to traverse a folder of the //1. folder NSString *myCachePath enumerator access [NSHomeDirectory (stringByAppendingPathComponent:@) = "Library/Caches"]; NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath]; __block NSUInteger count = 0; //2. (NSString *fileName for traversal in enumerator) {NSString * path = [myCachePath stringByAppendingPathComponent:fileName]; NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]; count = fileDict.fileSize; / / custom A cache size is byte into} / / M = totalSize (CGFloat (CGFloat) imageCacheSize+count) /1024/1024; return totalSize;}

43. Clean up the app cache

- (void handleClearView) {/ / delete two part //1. delete SD image cache to remove image cache [[SDImageCache sharedImageCache] / / clearMemory] / / in memory; [[SDImageCache sharedImageCache] clearDisk] clear disk cache; //2. *myCachePath = [NSHomeDirectory NSString delete their own cache (stringByAppendingPathComponent:@) "Library/Caches"]; [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];}

44, model to dictionary

Static NSSet *classes (NSMutableDictionary * getParameterDictionary); - {NSMutableDictionary *dict = [NSMutableDictionary dictionary]; Class C = self.class; while (c) {unsigned count; objc_property_t *properties = class_copyPropertyList ([c class], & count); for (int i = 0; I < count; i++) {NSString *key = [NSString (stringWithUTF8String:property_getName properties[i])]; dict[key] valueForKey:key] = [self;} free (properties); / / get the parent class C = class_getSuperclass (c); if ([self isClassFromFoundation:c]) break return dict;};} - (BOOL) isClassFromFoundation: (Class C) {if (C = = [NSObject class] = [NSManagedObje C || CT class] return YES __block BOOL); result = NO; [[self foundationClasses] enumerateObjectsUsingBlock:^ (Class foundationClass, BOOL *stop) {if ([c isSubclassOfClass:foundationClass]) {result = YES; *stop = YES;}}]; return result;} - (NSSet * foundationClasses) {if (classes = = Nil) {/ / set without NSObject. Because almost all classes are inherited from NSObject, the NSObject is not in need of special classes = [NSSet setWithObjects: [NSURL class] judge, [NSDate class], [NSData class], class] NSValue, [NSError class [NSArray class], [NSDictionary, class], [NSString class], [NSAttributedString class], nil] return classes;}};

45, exchange two methods to achieve

Class aClass = [self class]; SEL originalSelector = @selector (viewWillAppear:); SEL swizzledSelector = @selector (xxx_viewWillAppear:); Method originalMethod = class_getInstanceMethod (aClass, originalSelector); Method swizzledMethod = class_getInstanceMethod (aClass, swizzledSelector); BOOL didAddMethod = class_addMethod (aClass, originalSelector, method_getImplementation (swizzledMethod), method_getTypeEncoding (swizzledMethod) (if); didAddMethod (aClass) {class_replaceMethod, swizzledSelector, method_getImplementation (originalMethod), method_getTypeEncoding (or IginalMethod))} else {method_exchangeImplementations (originalMethod, swizzledMethod)}

46, print and sign Quotes

NSLog (@ "%"); NSLog ("/" @ ");

47, several commonly used authority judgment

If ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {NSLog (@ "No location permission");} AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (statusVideo = = AVAuthorizationStatusDenied) {NSLog (@ "no camera access");} / / have access to AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio] microphone; if (statusAudio = = AVAuthorizationStatusDenied) {NSLog (@ "no recording rights");} [PHPhotoLibrary requestAuthorization:^ (PHAuthorizationStatus status) {if (status = = PHAuthorizationStatusDenied) {NSLog (@ "no permissions album");} }];

48, access to mobile phone model

+ (NSString * getDeviceInfo) {struct utsname systemInfo; uname (& systemInfo); NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding]; if ([platform isEqualToString:@ "iPhone1,1"]) return @ "iPhone 2G"; if ([platform isEqualToString:@ "iPhone1,2"]) return @ "iPhone 3G"; if [platform ("iPhone2,1 isEqualToString:@" return @ "iPhone 3GS"); if ("[platform isEqualToString:@" iPhone3,1 "]) return @" iPhone 4 "(if; [platform isEqualToString:@" iPhone3,2 "]) return @" iPhone 4 "(if; [platform isEqualToString:@" iPhone3,3 "]) return @" iPhone 4 "; if ([platform" iPhone4,1 "isEqualToString:@ return @" iPhone 4S "); if (" [platform isEqualToString:@ "iPhone5,1" return "iPhone 5 @])" If ([platform; isEqualToString:@ "iPhone5,2"]) return @ "iPhone 5" (if; [platform isEqualToString:@ "iPhone5,3"]) return @ "iPhone 5C"; if ([platform isEqualToString:@ "iPhone5,4"]) return @ "iPhone 5C"; if ("platform isEqualToString:@" iPhone6,1 "return" iPhone ") @ 5S" if ([platform; isEqualToString:@ "iPhone6,2"]) return @ "iPhone 5S"; if ([platform isEqualToString:@ "iPhone7,1"]) return @ "iPhone 6 Plus" ([platform if; isEqualToString:@ "iPhone7,2"]) return @ "iPhone 6" (if; [platform isEqualToString:@ "iPhone8,1"]) return @ iPhone 6S; if ([platform "isEqualToString:@" iPhone8,2 "return" iPhone 6S ") @ Plus"; / / day two mobile phone models are Japan exclusive, payment may use the SONY FeliCa payment scheme instead of apple If ([platform isEqualToString:@ "iPhone9,1" return "]) @ state bank, Japan, Hong Kong iPhone 7; if ([platform isEqualToString:@" iPhone9,2 "return"]), in Hong Kong @ iPhone 7 Plus; if ([platform "isEqualToString:@" iPhone9,3 "]) return @" U.S. version, Taiwan version of iPhone 7 If ([platform; isEqualToString:@ "iPhone9,4"]) return @ "beauty version, Taiwan version of iPhone 7 Plus; if ([platform" isEqualToString:@ "iPhone8,4"]) return @ "iPhone SE"; if ("iPod1,1 [platform isEqualToString:@" return "iPod") @ Touch ([platform isEqualToString:@ if 1G ";" iPod2,1 "] return @ iPod) Touch ([platform isEqualToString:@ if 2G"; "iPod3,1" return "iPod Touch") @ 3G "; if ([platform isEqualToString:@" iPod4,1 "return" iPod ") @ Touch ([platform isEqua if 4G"; LToString:@ "iPod5,1" return "iPod") @ Touch ([platform isEqualToString:@ if 5G ";" iPad1,1 "]) return @" iPad 1G "; if ([platform isEqualToString:@" iPad2,1 "]) return @" iPad 2 "(if; [platform isEqualToString:@" iPad2,2 "]) return @ if (" iPad 2 "; [platform isEqualToString:@" iPad2,3 "]) return @" iPad 2 "(if; [platform isEqualToString:@" iPad2,4 "]) return @" iPad 2 "(if; [platform isEqualToString:@" iPad2,5 "return" iPad ") @ Mini ([platform isEqualToString:@ if 1G"; "iPad2,6" return "iPad Mini") @ 1G "; if ([platform isEqualToString:@" iPad2,7 "return" iPad ") @ Mini ([platform isEqualToString:@ if 1G"; "iPad3,1"]) return @ "iPad 3"; if ([platform isEqualToString:@] "iPad3,2") return @ "iPad 3" ([platform isEqualToStrin; if G:@ "iPad3,3"]) return @ "iPad 3" (if; [platform isEqualToString:@ "iPad3,4"]) return @ "iPad 4" (if; [platform isEqualToString:@ "iPad3,5"]) return @ "iPad 4" (if; [platform isEqualToString:@ "iPad3,6"]) return @ "iPad 4" ([platform; if isEqualToString:@ "iPad4,1" return "iPad") @ Air "; if ([platform isEqualToString:@" iPad4,2 "]) return @" iPad Air "; if ([platform isEqualToString:@" iPad4,3 "]) return @" iPad Air "; if (" platform isEqualToString:@ "iPad4,4" return "iPad Mini") @ 2G "; if (" [platform isEqualToString:@ iPad4,5 "return" iPad ") @ Mini ([platform isEqualToString:@ if 2G"; "iPad4,6" return "iPad") @ Mini ([platform isEqualToString:@ if 2G ";" i386 "]) return @" iPhone Simulator "; if ([platform isEqualToString:@ "X86_64")) return @ iPhone Simulator; return platform;}

49, long press copy function

- (void) viewDidLoad [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self {action:@selector} "; (pasteBoard:) - (void) pasteBoard: (UILongPressGestureRecognizer * longPress) {if (longPress.state = = UIGestureRecognizerStateBegan) {UIPasteboard *pasteboard [UIPasteboard = generalPasteboard]; pasteboard.string = @" need to copy the text ";}}

50, cocoapods upgrade

Sudo gem install -n / usr / local / bin cocoapods –pre is executed at the terminal

51, after setting up the start page, still displays the previous

Delete app, restart the phone, reinstall

52, determine the picture type

/ / the first byte of Data data through the picture to get the picture extension (NSString) - contentTypeForImageData: (NSData * data) {uint8_t C; [data getBytes:& C length:1]; switch (c) {case 0xFF: return @ "JPEG"; case 0x89: return; case 0x47: @ PNG return @ "GIF"; case 0x49: case 0x4D: return @ case "TIFF"; 0x52: if ([data length] < 12; return) {nil}; NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange (0, 12)] encoding: NSASCIIStringEncoding]; if ([testString hasPrefix:@ & & "RIFF"]; [testString; hasSuffix:@ "WEBP"]) { Return @ webp;} return nil;} return nil;}

53, access to mobile phones and app information

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; CFShow (infoDictionary); / / APP name NSString *app_Name [infoDictionary objectForKey:@ = "CFBundleDisplayName"]; / / APP version of NSString *app_Version objectForKey:@ [infoDictionary = "CFBundleShortVersionString"]; / / APP build version NSString *app_build objectForKey:@ [infoDictionary = "CFBundleVersion"]; / / mobile phone serial number NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier]; NSLog (@ "hand machine serial number:% @", identifierNumber); / / mobile phone user defined name alias: NSString* userPhoneName = [[UIDevice currentDevice] name]; NSLog (@ "mobile phone name:% @", userPhoneName); / / device name NSString* DeviceName = [[UIDevice currentDevice] systemName]; NSLog (@ "device name:% @", deviceName); / / mobile phone system version NSString* phoneVersion = [[UIDevice currentDevice] systemVersion]; NSLog (@ "mobile phone system version:% @", phoneVersion); / / phoneModel [[UIDevice currentDevice] mobile phone model NSString* = model]; NSLog (@ "mobile phone number:% @". PhoneModel); / / local model (NSString* localPhoneModel international domain name) = [[UIDevice currentDevice] localizedModel]; NSLog (@ "international domain name:% @", localPhoneModel); NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary] NSString *appCurName; / / current application name = [infoDictionary objectForKey:@ CFBundleDispl AyName "]; NSLog (@" the application name:% @ ", appCurName); / / the current version of the application such as: 1.0.1 NSString *appCurVersion [infoDictionary objectForKey:@ =" CFBundleShortVersionString "]; NSLog (@"% @ ": the current version of the application, appCurVersion); / / the current application version number int type NSString *appCurVersionNum = [infoDictionary objectForKey:@ CFBundleVersion"]; NSLog (@ "the current application version number:"% @ appCurVersionNum);

54. Get all the attributes of a class

ID LenderClass = objc_getClass ("Lender"); unsigned int outCount, I; objc_property_t *properties = class_copyPropertyList (LenderClass, & outCount); for (I = 0; I < outCount; i++) {objc_property_t property = properties[i]; fprintf (stdout, "%s%s/n", property_getName (property), property_getAttributes (property));}

55, image rounded corners

- (UIImage * circleImage) {/ / NO (self.size, NO, UIGraphicsBeginImageContextWithOptions on behalf of transparent, 1); / / CGContextRef CTX = UIGraphicsGetCurrentContext (context); / / add a circle CGRect rect = CGRectMake (0, 0, self.size.width, self.size.height); / / square variable circular CGContextAddEllipseInRect (CTX, rect); / / CGContextClip (clipping CTX); / / the picture painted [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext (UIGraphicsEndImageContext); (return); image;}

56, image stretch

+ (UIImage *) resizableImage: (NSString * imageName) {UIImage *image = [UIImage imageNamed:imageName]; CGFloat imageW = image.size.width; CGFloat = imageH image.size.height; return [image resizableImageWithCapInsets:UIEdgeInsetsMake (imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5 resizingMode:UIImageResizingModeStretch]);}

57, JSON string dictionary

+ (NSDictionary *) parseJSONStringToNSDictionary: (NSString * JSONString) {NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options: NSJSONReadingMutableLeaves error:nil]; return responseJSON;}

58, ID number verification

- (BOOL) validateIdentityCard if ({BOOL flag; self.length < = 0) {flag = NO; return = flag;} NSString *regex2 @ ^ (//d{14}|//d{17}) (//d|[xX]); *identityCardPredicate = $"NSPredicate [NSPredicate predicateWithFormat:@" SELF MATCHES, regex2] return% @ "; [identityCardPredicate evaluateWithObject:self];}

59. Get the device MAC address

+ (NSString * macAddress) {int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex ("en0")) = = 0) {printf ("Error: if_nametoindex error/n"); return NULL;} if (sysctl (MIB, 6, NULL, & len, < NULL, 0) 0) {printf ("Error: sysctl take 1/n"); return NULL;} (if (buf = malloc (len)) = = NULL) {printf ("Could not allocate memory. Rrror /n!"); return NULL;} if (sysctl (MIB, 6, buf, & len, < NULL, 0) 0) {printf ("Error: sysctl, take 2); return NULL;} IFM (struct = if_msghdr * buf); SDL = (struct * sockaddr_dl) (IFM + 1); PTR = (unsigned * char) LLADDR (SDL); NSString *outstring = [NSString stringWithFormat:@"%02X:% 02X:%02X:%02X:%02X:%02X "(*ptr, * ptr+1), * * (ptr+2), (ptr+3), * * (ptr+4), (ptr+5)]; free (buf); return outstring;}

60, import custom font library

1, find you want to use the font TTF format into
2, in the engineering project in plist and add a line array, “Fonts provided by application
3, the key add a item value for you just import the file name of the TTF
4, direct can be used: label.font = [UIFont fontWithName:@” you just import the TTF file name “size:20.0];

61, to get the current controller is displayed, whether push go in, or present can get in

- (UIViewController) getVisibleViewControllerFrom: (UIViewController*) VC ([vc isKindOfClass:[UINavigationController class]]) {if {return ([self getVisibleViewControllerFrom:[VC visibleViewController]] (UINavigationController*));} else if ([vc isKindOfClass:[UITabBarController class]]) {return ([self getVisibleViewControllerFrom:[VC selectedViewController]] (UITabBarController*));} else {if {return (vc.presentedViewController) [self getVisibleViewControllerFrom:vc.presentedViewController] else;} {return VC;}}}

62 and runtime add properties dynamically for a class

The dynamic nature of / / add attribute is: let the object of an attribute value associated with objc_setAssociatedObject (self, WZBPlaceholderViewKey, placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

63, get runtime for a class dynamically add attributes

Objc_getAssociatedObject (self, WZBPlaceholderViewKey);

64. KVO listens for the properties of an object

Add the listener [self addObserver:self forKeyPath:property / / options:NSKeyValueObservingOptionNew / / context:nil]; when the property value changes when will come to this method - (void) observeValueForKeyPath: (NSString *) keyPath ofObject: (ID) object change: (NSDictionary * Change) context: (void * context) {if ([keyPath isEqualToString:@ "property"]) {[self textViewTextChange]; {else}}}

65, Reachability determine network status

NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]; if (status = = NotReachable) {NSLog (@ "current equipment network");} if (status = = ReachableViaWiFi) {NSLog (@ "current WiFi network");} if (status = = NotReachable) {NSLog (@ the cellular mobile network ");}

66, AFNetworking monitor network status

Monitoringthenetworkstatusandthedatatransmission AFNetworkReachabilityManager / / *mgr = [AFNetworkReachabilityManager sharedManager]; [mgr setReachabilityStatusChangeBlock:^ (AFNetworkReachabilityStatus status) {switch (status) {case AFNetworkReachabilityStatusUnknown: break; case AFNetworkReachabilityStatusNotReachable: {[SVProgressHUD showInfoWithStatus:@ "current network equipment"]}; break; case AFNetworkReachabilityStatusReachableViaWiFi: [SVProgressHUD showInfoWithStatus:@ "the Wi-Fi network"]; break; case AFNetworkReachabilityStatusReachableViaWWAN: [SVProgressHUD showInfoWithStatus:@ "the bee Cellular mobile network "]; break; default: break;}}]; [mgr startMonitoring];

67, transparent colors do not affect the transparency of the sub view

[UIColor colorWithRed:< (CGFloat) #; #> green:< # (CGFloat) #> blue:< # (CGFloat) #> alpha:< #> # (CGFloat)];

68, take pictures of a point of color

If (point.x < point.y < ||; 0; 0) return nil CGImageRef; imageRef = self.CGImage; NSUInteger = width CGImageGetWidth (imageRef); NSUInteger height = CGImageGetHeight (imageRef) if (point.x; > = width; point.y = > ||; height return nil; unsigned char) *rawData = malloc (height * width * 4 if (rawData); return nil; CGColorSpaceRef!) (NSUInteger) colorSpace = CGColorSpaceCreateDeviceRGB; bytesPerPixel = 4; NSUInteger = bytesPerRow bytesPerPixel * width NSUInteger CGContextRef; bitsPerComponent = 8; context = CGBitmapContextCreate (rawData, width, height, BitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (! Context) {free (rawData); return nil;} CGColorSpaceRelease (colorSpace); CGContextDrawImage (context, CGRectMake (0, 0, width, height, imageRef)); CGContextRelease (context); int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel; CGFloat red = (rawData[byteIndex] * 1) / 255; CGFloat (green = rawData[byteIndex + 1] * 1 / 255); CGFloat (blue = rawData[byteIndex + 2] * 1 / 255); CGFloat (alpha = rawData[byteIndex + 3] * 1 / 255); UIColor *result = nil; result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha] free (rawData); return; result;

69, determine whether the transparency of the picture channel

- hasAlphaChannel (BOOL) {CGImageAlphaInfo alpha = CGImageGetAlphaInfo (self.CGImage); return (alpha = = kCGImageAlphaFirst alpha = kCGImageAlphaLast alpha || || || = = kCGImageAlphaPremultipliedFirst alpha = = kCGImageAlphaPremultipliedLast);}

70, get grayscale

(UIImage*) + covertToGrayImageFromImage: (UIImage*) sourceImage width int {int = sourceImage.size.width; height = sourceImage.size.height; CGColorSpaceRef = colorSpace; context = CGContextRef (CGColorSpaceCreateDeviceGray) CGBitmapContextCreate (nil, width, height, 8,0, colorSpace, kCGImageAlphaNone); CGColorSpaceRelease (colorSpace); if (context = = NULL) {return} (context nil; CGContextDrawImage (0, 0, CGRectMake, width, height), sourceImage.CGImage); CGImageRef contextRef = CGBitmapContextCreateImage (context); UIImage *grayImage = [UIImage imageWithCGImage:contextRef]; CGContextRelease (context); CGImageRelease (contextRef); return grayImage;}

71, according to the file name in bundle to read pictures

+ (UIImage *) imageWithFileName: (NSString * name) {NSString *extension = @ "PNG"; NSArray *components = [name componentsSeparatedByString:@ "]." ([components count]; if > NSUInteger = 2) {lastIndex = components.count - 1; extension = [components objectAtIndex:lastIndex]; name [name = substringToIndex: (name.length- (extension.length+1))]; Retina} / / if screen and there are pictures, returns Retina pictures, or find common picture if ([UIScreen mainScreen].Scale = = 2) {name [name stringByAppendingString:@ = "@2x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path! = Nil) {return [UIImage imageWithContentsOfF Ile:path] ([UIScreen mainScreen].scale if;}} = = 3) {name [name stringByAppendingString:@ = "@3x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path! = Nil) {return}} [UIImage imageWithContentsOfFile:path]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if return [UIImage (path) {imageWithContentsOfFile:path]}; return nil;}

72, merge two pictures

(UIImage*) + mergeImage: (UIImage*) firstImage withImage: (UIImage*) secondImage firstImageRef CGFloat {CGImageRef = firstImage.CGImage; firstWidth = CGImageGetWidth; firstHeight = CGFloat (firstImageRef) CGImageGetHeight (firstImageRef); CGImageRef secondImageRef = secondImage.CGImage; CGFloat = secondWidth CGImageGetWidth (secondImageRef); CGFloat secondHeight = CGImageGetHeight (secondImageRef); CGSize mergedSize = CGSizeMake (MAX (firstWidth, secondWidth, MAX) (firstHeight, secondHeight)); UIGraphicsBeginImageContext (mergedSize); [firstImage drawInRect:CGRectMake (0, 0, firstWidth, firstHeight); [secondImage drawInRect:CGRectMake (0, 0, secondWidth, secondHeight); UIImage *image = UIGraphicsGetImageFrom CurrentImageContext (); UIGraphicsEndImageContext (); return image;}

73, create a ImageView based on the image name in bundle

+ (ID) imageViewWithImageNamed: (NSString*) imageName {return, [[UIImageView, alloc], initWithImage:[UIImage, imageNamed:imageName]],}

74, add an inverted image for imageView

CGRect frame = self.frame; frame.origin.y = (frame.size.height + 1); UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame]; self.clipsToBounds = TRUE; reflectionImageView.contentMode = self.contentMode; reflectionImageView.transform = reflectionImageView [setImage:self.image]; CGAffineTransformMakeScale (1, -1.0); CALayer *reflectionLayer = [reflectionImageView layer]; CAGradientLayer *gradientLayer [CAGradientLayer = layer]; gradientLayer.bounds = reflectionLayer.bounds; gradientLayer.position = CGPointMake (reflectionLayer.bounds.size.width / 2 reflectionLayer.bounds.size.height, * 0.5); gradientLayer.colors (id = [NSArray arrayWithObjects: [[UIColor clearColor] CGColor] (ID), [[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3]) CGColor], nil]; gradientLayer.startPoint = CGPointMake; gradientLayer.endPoint = (0.5,0.5) CGPointMake (0.5,1.0); reflectionLayer.mask = gradientLayer; [self.superview addSubview:reflectionImageView];

75. Draw watermarks

/ / - (void) setImage: picture watermark (UIImage * image) withWaterMark: (UIImage *) mark inRect: (CGRect) Rect ([[[UIDevice currentDevice] systemVersion] floatValue] {if > = 4) {UIGraphicsBeginImageContextWithOptions (self.frame.size, NO, 0);} / / drawInRect:self.bounds] / / [image image watermarking; drawInRect:rect] UIImage *newPic = [mark; (UIGraphicsGetImageFromCurrentImageContext) (UIGraphicsEndImageContext);; self.image = newPic;}

76. Let the text of label be displayed at the upper left / right upper / lower left / right lower / center top / center bottom

The custom textRectForBounds method UILabel / / rewrite label - (CGRect) textRectForBounds: (CGRect) bounds limitedToNumberOfLines: (NSInteger) numberOfLines rect textRectForBounds:bounds limitedToNumberOfLines:numberOfLines] {CGRect = [super; switch (self.textAlignmentType) {case} WZBTextAlignmentTypeLeftTop: {rect.origin = bounds.origin; break; case WZBTextAlignmentTypeRightTop: {rect.origin = CGPointMake (CGRectGetMaxX (bounds) - rect.size.width, bounds.origin.y, break);} case; WZBTextAlignmentTypeLeftBottom: {rect.origin = CGPointMake (bounds.origin.x, CGRectGetMaxY (bounds) - rect.size.height}); break; case WZBTextAlignmentTypeRightBottom: {rect.origin = CGPointMake (CGRectGetMaxX (bounds) - rect.size.width, CGRectGetMaxY - rect.size.height (bounds));} case {rect.origin = break; WZBTextAlignmentTypeTopCenter: CGPointMake ((CGRectGetWidth (bounds) - CGRectGetWidth (rect) / 2), CGRectGetMaxY (bounds) - rect.origin.y);} case {rect.origin = break; WZBTextAlignmentTypeBottomCenter: CGPointMake ((CGRectGetWidth (bounds) - CGRectGetWidth (rect) / 2), CGRectGetMaxY (bounds) - CGRectGetMaxY (bounds) - rect.size.height);} case {rect.origin = break; WZBTextAlignmentTypeLeft: CGPointMake (0, rect.origin.y);} Break; case WZBTextAlignmentTypeRight: {rect.origin = CGPointMake (rect.origin.x, 0);} case {rect.origin = break; WZBTextAlignmentTypeCenter: CGPointMake ((CGRectGetWidth (bounds) - CGRectGetWidth (rect) / 2 (CGRectGetHeight), (bounds) - CGRectGetHeight (rect)) / 2}); break default:; break return rect;}}; - (void) drawTextInRect: (CGRect) rect textRect textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines] {CGRect = [self; [super drawTextInRect:textRect];}

77, scrollView on the input box, the keyboard blocked the problem

The framework for IQKeyboardManager is recommended! The manual to solve the following 1 monitoring / keyboard popup notify 2, disappeared in the notice to join the info Code: NSDictionary* = [aNotification userInfo]; CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view]; CGSize kbSize =keyPadFrame.size; CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview] CGRect; aRect = self.view.bounds; aRect.size.height = (kbSize.height) CGPoint; origin = activeRect.origin; origin.y = backScrollView.contentOffset.y; if (! CGRectContainsPoint (aRect, origin) {CGPoint = CGPointMake (scrollPoint) 0, CGRectGetMaxY (activeRect) - (aRect.size.height)); [backScrollView setContentOffset : scrollPoint animated:YES];}

78, frame layout of the cell dynamic height

This usually adds an auxiliary attribute cellHeight to your model, and overrides the get method in the model, which calculates the total height based on your layout and other attribute values in the model. Finally, in the tableView:heightForRow method, you can find the corresponding model according to indexPath and return to this height.

79, AutoLayout layout of the cell dynamic height

1, setting the properties of tableView / self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 44; / / this property is not 0, cell height estimation
2 /, top-down set cell constraints, note that it is best to be the top down to cell around
Years of experience in iOS development (1)

80 、 use performSelector: call function, memory leak problem

When we use [obj in the development of performSelector:NSSelectorFromString (@ aMethod)]; may receive a warning of “performSelector may cause a leak because its selector is unknown
.” this kind of method is because the compiler does not know the object can corresponding to this method, if not, it is not safe, and the return value is also not clear how to deal with this method!

Use the following code can be called: if (! Obj) {return}; SEL selector = NSSelectorFromString (@ aMethod); IMP imp = [obj methodForSelector:selector]; void (*func) (ID, SEL) = (void *) imp; func (obj, selector); or: SEL selector = NSSelectorFromString (@ "aMethod" (;) (void (*) (ID, SEL) [obj) methodForSelector:selector]) (obj, selector);

81, whether a string contains another string

Methods 1 if ([str1 / containsString:str2]) {NSLog (@ STR1 contains STR2 ");} else {NSLog (@ STR1 does not contain STR2");} / / if ([str1 rangeOfString: str2].location 2 = = NSNotFound) {NSLog (@ STR1 contains STR2 ");} else {NSLog (@ STR1 does not contain STR2");}

82, cell to remove the selected effect

Cell.selectionStyle = UITableViewCellSelectionStyleNone;

83, cell point, press the effect

- - (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {[tableView deselectRowAtIndexPath:indexPath animated:YES]}

84, when deleting a drag out from the Xib property, make sure that you have the corresponding Xib line also deleted, otherwise will be reported similar to [< ViewController 0x7fea6ed05980> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key crash

Years of experience in iOS development (1)
click on this fork number to delete

85, testing error: Could not launch “you App”, process launch failed: Security

Since your app is not on-line, iOS9 begins with the need to manually trust the Xcode generated description file, open the cell phone settings -> general -> describe the file -> click on your app description file -> click trust

86, testing error: Could not find Developer Disk Image

This is because your device system version is larger than the Xcode compatible system version, such as your device is iOS10.3, and the Xcode version is 8.2 (Xcode8.2 maximum compatible iOS10.2), you will report this error. The solution is to upgrade Xcode!

87, UITextView, no placeholder problem?

There are many such online custom control, but also can refer to the UITextView-WZB I wrote a UITextView classification

88, remove space and line breaks in strings

+ (NSString *) removeSpaceAndNewline: (NSString * STR) {NSString *temp = [str "stringByReplacingOccurrencesOfString:@" withString:@ "temp [temp stringByReplacingOccurrencesOfString:@"]; = "/r" withString:@ "]; temp stringByReplacingOccurrencesOfString:@ [temp =" /n "withString:@"]; return temp;}

89, determine whether there is space in the string

(BOOL) + isBlank: (NSString * STR) {NSRange _range = [str "rangeOfString:@"]; if (_range.location! = NSNotFound) {/ / return else spaces YES;} {/ / no spaces return NO;}}

90. Get the first frame of a picture

NSURL *url = [NSURL URLWithString:filepath]; AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil]; AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1]; generate1.appliesPreferredTrackTransform = YES; NSError = *err NULL; CMTime time = CMTimeMake (1, 2); CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:& err]; UIImage *one = [[UIImage alloc] initWithCGImage:oneRef]; return one;

91, the length of the video capture

(NSInteger) + getVideoTimeByUrlString: (NSString * urlString) {NSURL *videoUrl = [NSURL URLWithString:urlString]; AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl]; CMTime time = [avUrl duration]; int seconds = ceil (time.value/ time.timescale); return seconds;}

92, string is empty

(BOOL) + isEqualToNil: (NSString * STR) {return str.length < [str isEqualToString:@ = 0 || "] || str;}!

93, when you upload app to App Store, you usually encounter this problem

Years of experience in iOS development (1)
try again

Many people say that apple, Dad, server problems, repeated attempts a few times, will always succeed!
, but after trying to find that if you use the Application Loader upload success rate is very high, so it is recommended to export IPA files directly using Application Loader upload.
if Application Loader doesn’t work, you need to check your network, and sometimes VPN speeds up too.

94, when the tableView occupies a screen, remove the excess cells below

Self.tableView.tableHeaderView = [UIView new]; self.tableView.tableFooterView = [UIView new];

95, the difference between isKindOfClass and isMemberOfClass

IsKindOfClass can determine whether an object belongs to a class, or to subclasses of that class. IsMemberOfClass is more precise, and it can only determine whether the object type is the class (which cannot be judged by subclasses)

96, __block

When a local variable needs to be changed in block, to the definition of __block plus modified, please see the official document

97, -[ViewController, aMethod:]: unrecognized, selector, sent, to, instance, 0x7fe91e607fb0

This is a classic error, and ViewController cannot respond to the aMethod method. The wrong reason might not be implemented in the viewController file, aMethod

98, UITableView (< UITableView: 0x7ff19b027000; >) failed, to, obtain, a, cell, from, its, dataSource (< ViewController:; 0x7ff19a507520>);

The reason for this error is that tableView’s proxy method, -tableView:cellForRowAtIndexPath:, needs to return a UITableViewCell, and you return a nil. In addition, the return value of this place is not UITableViewCell type, but it also causes a crash

99, constraints on how to do UIView animation?

1, the constraints of Constraint needs to be modified drag lines, attributes to be in 2, require animation places to join the code, the constant property change this property 3, start the UIView animation, @property animation, it calls the layoutIfNeeded method (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint; self.buttonTopConstraint.constant = 100; [UIView animateWithDuration:.5 animations:^{[self.view layoutIfNeeded]}];

100. Get the link string from NSURL

NSString *urlString = myURL.absoluteString;

101. Scroll tableView to the top

[tableView setContentOffset:CGPointZero animated:YES]; or [tableView scrollRectToVisible:CGRectMake (0, 0, 1, 1) animated:YES];

102, if the addTarget:action:forControlEvents: method for a button to add a lot of click events, at a certain time want to delete once, how to do? Just call the following code

[youButton removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];

103, the height of a font


104, delete all child views of a view

[[someView, subviews], makeObjectsPerformSelector:@selector (removeFromSuperview)];

105, delete all records of NSUserDefaults

A method of NSString = [[NSBundle *appDomain / mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; / / two - (void) resetDefaults * defs [NSUserDefaults standardUserDefaults] {NSUserDefaults = NSDictionary; dict = [defs * dictionaryRepresentation]; for (ID key in dict) {[defs removeObjectForKey:key]}; [defs synchronize];} / / [[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle three mainBundle] bundleIdentifier]];

106, disable system sliding return function

- (void) viewDidAppear: (BOOL) animated if ({[super viewDidAppear:animated]; [self.navigationController respondsToSelector:@selector (interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;}} - (void) viewWillDisappear: (BOOL) animated if ({[super viewWillDisappear:animated]; [self.navigationController respondsToSelector:@selector (interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;}} - (BOOL) gestureRecognizerShouldBegin: (UIGestureRecognizer *) gestureRecognizer {return NO;}

107 simulator error

Years of experience in iOS development (1)
simulator error

The solution:
opens the emulator -> Simulator-> Reset Content and Settings…
; if not, restart it!

108, custom cell select the background color

UIView *bgColorView = [[UIView, alloc], init]; bgColorView.backgroundColor = [UIColor, redColor]; [cell setSelectedBackgroundView:bgColorView];

109, UILabel sets the inner margin

Subclass UILabel and override the drawTextInRect method - (void) drawTextInRect: (CGRect rect) {/ / on the left and right margins, UIEdgeInsets insets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect (rect, insets);}

110, UILabel set text strokes

Subclass UILabel and override the drawTextInRect method - (void) drawTextInRect: (CGRect) Rect (c) {CGContextRef = UIGraphicsGetCurrentContext; / / set the stroke width of CGContextSetLineWidth (C, 1); CGContextSetLineJoin (C, kCGLineJoinRound); CGContextSetTextDrawingMode (C, kCGTextStroke); / / self.textColor = [UIColor color color redColor]; [super drawTextInRect:rect]; / / text color self.textColor = [UIColor yellowColor]; CGContextSetTextDrawingMode (C, kCGTextFill); [super drawTextInRect:rect];}

111, using the simulator screenshot

Shortcut keys Command + s,
or File-> Save Screen Shot

112, scrollView scroll to the bottom

CGPoint bottomOffset = CGPointMake (0, scrollView.contentSize.height - scrollView.bounds.size.height); [scrollView, setContentOffset:bottomOffset, animated:YES];

113, UIView background color gradient

UIView *view = [[UIView alloc] initWithFrame:CGRectMake (0, 0, 320, 100)]; [self.view addSubview:view]; CAGradientLayer *gradient [CAGradientLayer = layer]; gradient.frame = view.bounds; gradient.colors = [NSArray arrayWithObjects: (ID) [[UIColor blackColor] CGColor] (ID) [[UIColor whiteColor] CGColor], nil] [view.layer insertSublayer:gradient atIndex:0];

114, stop UIView animation

[yourView.layer removeAllAnimations]

115, add a fillet for a corner of UIView

/ / the upper left and lower right corners add *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners: round UIBezierPath (UIRectCornerTopLeft UIRectCornerBottomRight |) cornerRadii:CGSizeMake (20, 20) CAShapeLayer *maskLayer = [CAShapeLayer]; layer]; maskLayer.frame = view.bounds; maskLayer.path = maskPath.CGPath; view.layer.mask = maskLayer;

116, delete Xcode, Derived, data cache data

Click the Xcode -> Preferences -> location Derived data, and then click on the path to the small arrow, delete the folder data on it, such as Years of experience in iOS development (1)
Xcode Derived data

117, place a view at the top of its sibling view

[parentView bringSubviewToFront:yourView]

118, place a view at the bottom of its sibling view

[parentView sendSubviewToBack:yourView]

119, let mobile phone vibration

Load the frame #import < AudioToolbox/AudioToolbox.h> AudioServicesPlayAlertSound (kSystemSoundID_Vibrate); or AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);

– (BOOL) isEqualToColor: (UIColor * otherColor) {CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB (UIColor); * (^convertColorToRGBSpace) (UIColor*) (UIColor = ^ {if (*color) CGColorSpaceGetModel (CGColorGetColorSpace (color.CGColor)) = = kCGColorSpaceModelMonochrome) {const CGFloat *oldComponents = CGColorGetComponents (color.CGColor); CGFloat components[4] = {oldComponents[0], oldComponents[0], oldComponents[0]. OldComponents[1]}; CGColorRef colorRef = CGColorCreate (colorSpaceRGB, components); UIColor *color = [UIColor colorWithCGColor:colorRef]; CGColorRelease (colorRef); return color; else return color}}; UIColor *selfColor = convertColorToRGBSpace (self); otherColor = convertColorToRGBSpace (otherColor); CGColorSpaceRelease (colorSpaceRGB); return, [selfColor, isEqual:otherColor];}

135, tableViewCell split line top to the end

– (void) tableView: (UITableView * tableView) willDisplayCell: (UITableViewCell * cell) forRowAtIndexPath: (NSIndexPath * indexPath) {[cell setSeparatorInset:UIEdgeInsetsZero]; [cell setLayoutMargins:UIEdgeInsetsZero]; cell.preservesSuperviewLayoutMargins = NO;} – {[self.tableView (void) viewDidLayoutSubviews setSeparatorInset:UIEdgeInsetsZero]; [self.tableView setLayoutMargins:UIEdgeInsetsZero];}

136, do not allow the view of the controller to be stretched or compressed with the Xib of the controller

Self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth UIViewAutoresizingFlexibleHeight |;

Unable, cocoaPods, to, add, a, source, with, URL,, named, master-1.,

You, can, try, adding, it, manually, in, ~/.cocoapods/repos, or, via,, pod, repo, add.

Solution: This is because the computer installed another Xcode, causing cocoapods can not find the path, 
in the terminal to execute sudo xcode-select -switch /Applications/ can be

138, when installing cocoapods, appear ERROR:, While, executing, gem… (Errno:: EPERM)

Operation not permitted - /usr/bin/pod

The solution: execute sudo gem install -n /usr/local/bin cocoapods directly at the terminal

139, in the status bar to increase network request chrysanthemum, similar to safari loading page status bar Chrysanthemum

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

140, check whether a rect contains a point

Whether in the rect / / point BOOL isContains = CGRectContainsPoint (rect, point);

141, at the specified width, let UILabel automatically set the best font

Label.adjustsFontSizeToFitWidth = YES;

142. Save a image in an album

UIImageWriteToSavedPhotosAlbum (image, nil, nil, nil or #import); < Photos/Photos.h> [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage: = [NSDate image]; changeRequest.creationDate date];} completionHandler:^ (BOOL success, NSError *error) {if (success) {NSLog (@ “successfully saved”);} else {NSLog (@ error saving to photos:, error);}% @}];

143, modify the size of cell.imageView

UIImage *icon = [UIImage “imageNamed:@”]; CGSize itemSize = CGSizeMake (30, 30); UIGraphicsBeginImageContextWithOptions (itemSize, NO, 0); CGRect imageRect = CGRectMake (0, 0, itemSize.width, itemSize.height); [icon drawInRect:imageRect]; cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext (UIGraphicsEndImageContext ());

144, add a dotted border for a view

CAShapeLayer *border = [CAShapeLayer layer]; border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor; border.fillColor = nil; border.lineDashPattern = @[@4, @2]; border.path [UIBezierPath = bezierPathWithRect:view.bounds].CGPath; border.frame = view.bounds; [view.layer addSublayer:border];

145, UITextView open or disable the copy, cut, selection, select and other functions

UITextView / / inheritance override this method – (BOOL) canPerformAction: (SEL) action withSender: (ID sender) {/ / return to NO for the disabled, YES is open / paste if (action = = @selector (paste:) return) NO (action = = if; / / shear @selector (cut:) return) NO (action = = if; / / copy @selector return NO (copy:)); / / if (action = = @selector (select:)) return NO; / / select all the if (action = = @selector return NO (selectAll:)); / / delete if (action = = @selector (delete:)) return NO; / / if share (action = = @selector (share)) return NO return [super; canPerformAction:action withSender:sender];}

Because Jane book on the length of the article has certain restrictions, can only be written in sections, interested friends can continue to pay attention, there are many behind! The code in question can directly contact me or join our group together to exchange technology.

More of my articles: old drivers take you flying

Please do not spare, pick up a favorite or pay attention to it! Your support is my biggest motivation! 
you can follow me to check my latest article, if you have any questions about this article, please feel free to contact me, you can also join our group, family and look forward to your joining!

Years of experience in iOS development (1),
, our community

It’s because your cell was called early. The cell is first recycled, and then cell is created. The order is wrong

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    [cell setLayoutMargins:UIEdgeInsetsZero];
    cell.preservesSuperviewLayoutMargins = NO;

- (void)viewDidLayoutSubviews {
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];


self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

137、cocoaPods报错 : [!] Unable to add a source with url named master-1.

You can try adding it manually in ~/.cocoapods/repos or via pod repo add.

在终端执行 sudo xcode-select -switch /Applications/ 即可

138、安装cocoapods的时候出现 ERROR: While executing gem … (Errno::EPERM)

Operation not permitted - /usr/bin/pod

解决办法:直接在终端执行 sudo gem install -n /usr/local/bin cocoapods


[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


// point是否在rect内
BOOL isContains = CGRectContainsPoint(rect, point);


label.adjustsFontSizeToFitWidth = YES;


UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

#import <Photos/Photos.h>
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        changeRequest.creationDate          = [NSDate date];
    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"successfully saved");
        else {
            NSLog(@"error saving to photos: %@", error);


UIImage *icon = [UIImage imageNamed:@""];
CGSize itemSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[icon drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();


 CAShapeLayer *border = [CAShapeLayer layer];
    border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
    border.fillColor = nil;
    border.lineDashPattern = @[@4, @2];
    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
    border.frame = view.bounds;
    [view.layer addSublayer:border];


// 继承UITextView重写这个方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
// 返回NO为禁用,YES为开启
    // 粘贴
    if (action == @selector(paste:)) return NO;
    // 剪切
    if (action == @selector(cut:)) return NO;
    // 复制
    if (action == @selector(copy:)) return NO;
    // 选择
    if (action == @selector(select:)) return NO;
    // 选中全部
    if (action == @selector(selectAll:)) return NO;
    // 删除
    if (action == @selector(delete:)) return NO;
    // 分享
    if (action == @selector(share)) return NO;
    return [super canPerformAction:action withSender:sender];




Years of experience in iOS development (1)