Deep copy, shallow copy

In the case of the deep copy, the shallow copy has Pointers on the stack, memory is on the heap, and in the shallow copy, an extra pointer is generated on the stack &str &copystr, which prints at different addresses, but both Pointers point to the same block of memory on the heap. For nsstrings, too complicated, can be a constant area, also may be the heap, here to distinguish between the strong and the copy is self copystr = xx, calls the STR copy copy of a copy, STR modification does not affect the copy, but the strong with the changes. For a collection class, if the pointer address is the same, if you change the data, you change the content of the same pointer address, When debugging watch [[NSMutableArray alloc] initWithArray: mutalbearray copyItems: YES] element is a mutable object, modify the element and use completely copy of the file archiving solution

  • To regain the iOS – copy

KVO

132.0 and 1 unequal width solution:

  1. 2. Comments have a good solution

www.cocoachina.com/bbs/read.ph…

Json online parsing website

www.json.cn ,postman chyy

130. Handling method of 100 sets of equipment

Login administrator Account Account – > the memberShip – > Team ID developer.apple.com/contact/sub…

Blog.csdn.net/imanapple/a…

The purpose of overriding this method is to be able to intercept all controllers pushed in by @param viewController

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{ if (self.viewControllers.count > 0) {/ / controller viewController push came in at this moment, is not the first child (not the root controller) controller / * auto show and hide tabbar * / viewController. HidesBottomBarWhenPushed = YES; / * set the contents of the navigation bar above * / / / set the back button on the left viewController. NavigationItem. LeftBarButtonItem = [UIBarButtonItem itemWithTarget: self action:@selector(back) image:@"navigationbar_back" highImage:@"navigationbar_back_highlighted"]; / / set to the right of the more button viewController. NavigationItem. RightBarButtonItem = [UIBarButtonItem itemWithTarget: self action:@selector(more) image:@"navigationbar_more" highImage:@"navigationbar_more_highlighted"]; } [super pushViewController:viewController animated:animated]; }Copy the code
[[000]LLDB: expr = nil

Git add ignore file:www.gitignore.io

An empty directory submission find. -type d – empty – the exec touch {} /. THT blog.csdn.net/jeffasd/art… Delete UserInterfaceState. The ultimate method of xcuserstate file

ICYP0 MBProgressHUD [MBProgressHUD detailsLabel]: Unrecognized selector sent to instance

Clean up xcode cache gitee.com/oschina/iph…

125. Customized buttons in the iOS navigation bar cause the problem of too wide clicking range

Blog.csdn.net/github_2667…

124. App statistics check website

www.appannie.com/account/log…

123. The pod upgrade

  • Version upgrade blog.csdn.net/potato512/a…
  • Warehouse upgrade www.jianshu.com/p/37fa98220…

122. When the review is rejected or waiting for the review, remove only needs to change the build. The version is for Apple to see, and the build is for the development to see

A version can have an unlimited number of builds and you can select one for final review

121. TestFight Appstore Beta

www.jianshu.com/p/684e4b56b…

120. Comparison of timestamp days

I’m going to take 30 times 24 times 60 times 60 times 0.0001

119. The app icon

icon.wuruihong.com/

118. Page jump push multiple times

Background color to set memory leak

117. The server returns NSNumber

Json nsstrings * = @ "{\" number \ ": 66.51}"; NSData* data = [json dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; id object = dic[@"number"]; NSLog(@"%@",[object class]); NSLog(@"%@",object);Copy the code

Output NSNumber 66.519999999999

116. Json string contains “” problem

www.jianshu.com/p/c7ecc1100…

115. Seven niuyun image processing

Scale [UIScreen mainScreen]. Scale? imageView/3/w/100/h/100

114. Picture rules

Shimo. Im/doc/o3wdQ9M…

113. HidesBottomBarWhenPushed = yes the correct use of the position

www.isaced.com/post-223.ht…

112. Ios10.3 uilabel Underline invalid

www.mamicode.com/info-detail…

111. Using classification (i.e. AOP)

Adding self to the current VC logic handler has the disadvantage of increasing compile time

110. Wkwebview reloads JS

Removefromsupview uiView = UIView

109. Coordinate system transformation

Finally, you can use KeyWindow

108. Save to album in iOS11

[assetsLibrary assetForURL:assetURL resultBlock] There is a high probability that retrieving videos from albums will fail. Solution: Replace AVAsset with PHAsset. You can do it by traversal or something else, in your notes

107.NSMutableArray *toolbarButtons = [self.navigationItem.rightBarButtonItems mutableCopy];

toolbarButtons removeobject:

106. The viewdidload frameb

105. Sometimes, the project navigation bar shows nothing but “No filter Results” and it doesn’t work to turn off and restart Xcode.

Solution: Enter any character in the search box below the navigation bar, and your project file directory will appear in the navigation bar.

NSDate daylight saving time winter time problem

Format. TimeZone = [NSTimeZone timeZoneWithName:@”UTC “]; Just add this (from giliangui’s solution)

103. Download the specified folder on Github

Link: www.zhihu.com/question/25…

For example this project: Mooophy/Cpp-Primer · GitHub, I just want to see the ch03 folder code? Open ch03 and its URL is: “HTTPS: //github.com/mooophy/cpp-primer /tree/master/ch03″(add space here to prevent zhihu intelligent recognition)

Replace /tree/master/ with /trunk/. (This should be familiar to anyone who used to play Google Code.) “HTTPS: //github.com /Mooophy/ cpp-primer /trunk/ch03″(also with Spaces)

Then, type:

SVN checkout github.com/Mooophy/Cpp…

PS: If you use it for the first time, the following prompt may appear:

R)eject, accept (t)emporarily or accept (p)ermanently?

Just type in P.

102. Download the specified SVN version

101. Delete the SVN folder

Delete “SVN” folder Delete the directory, it is very simple, the command is find. -type d – the name “SVN” | xargs rm – rf; Type d -iname “. SVN “-exec rm -rf {};

100. An Assertion failure in – [UITableView _endCellAnimationsWithContext:] – error

When deleting, be sure to have the same number of sections and rows. Otherwise it is easy to lead to the above error.

- (NSInteger) numberOfSectionsInTableView theTableView: (UITableView *) {/ / deletion of maintain the same number of section, otherwise, easy to cause the error above. if(self.totalArray.count>0) return 1; else return 0; } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {// set the corresponding row, can edit YLMessageModel* item=[self.totalArray objectAtIndex:indexPath.row]; if(item.msg_id<0) return NO; else return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { NSInteger r = indexPath.row; NSInteger c = indexPath.section; YLMessageModel* item=[self.totalArray objectAtIndex:r]; [self.totalArray removeObjectAtIndex:r]; [msgView beginUpdates]; [msgView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; If (self.totalarray. count==0){[msgView deleteSections:[NSIndexSet indexSetWithIndex:c] withRowAnimation:UITableViewRowAnimationFade]; } [msgView endUpdates]; }else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } }Copy the code

Blog.csdn.net/oqqquzi1234…

99. Make a distinction between event passing and responder linking:

The best control for handling the event is found through event passing, and the event bubbling process is performed through responder links.

The process of passing a response to a complete touch event

(The following line is the event lookup process)

UIAppliction –> UIWindow recursively finds the control that is best suited to handle the event. The control calls the Touches method –> Checks whether the Touches method is implemented –> Does not implement the event by default (The top line is the responder link)

  • Responder chain: A chain consisting of many responder links called responder chain
  • Responder: Objects that inherit from UIResponder are called responder objects

IOS UI Development – Event Delivery – Text Top – Blog park

98. HitTest :withEvent: method

When iOS detects a Touch, it puts it into the event queue of the current active Application. UIApplication pulls the Touch event from the event queue and passes it to the key Window (the window currently receiving the user event) for processing. The Window object first finds the initial point of the Touch operation using the hitTest:withEvent: method The View in which the touch event needs to be passed to its processing is called a hit-test View.

The window object will call hitTest:withEvent:, on the top view first in View Hierarchy. This method calls pointInside:withEvent: on each view in the view hierarchy. If pointInside:withEvent: returns YES, the call continues until it finds where the touch operation occurred. This view is also called the Hit-test view.

The hitTest:withEvent: method is handled as follows:

1. First call the pointInside:withEvent: method of the current view to determine whether the touch point is in the current view; If NO is returned, hitTest:withEvent: returns nil; If YES is returned, a hitTest:withEvent: message is sent to all subviews of the current view, traversal from top to bottom. That is, traversal from the end of the subviews array until any subviews return non-empty objects or all subviews are traversed. The first time a subview returns a non-empty object, the hitTest:withEvent: method returns the object. If all subviews return no, the hitTest:withEvent: method returns itself (self). The hitTest:withEvent: method ignores views that are hidden (hidden=YES), views that are prohibited from user action (userInteractionEnabled=YES), and views whose alpha level is less than 0.01(alpha<0.01). If a subview’s area exceeds the bound area of the parent view (the parent view clipsToBounds attribute is NO, so that the contents of the subview that exceeds the bound area of the parent view are displayed), Then normally touches on areas outside the parent view of the child are not recognized because the parent view’s pointInside:withEvent: method returns NO, so it does not continue down through the child view. Of course, you can override the pointInside:withEvent: method to handle this case. IOS hard to understand a few screen contact issues – small wave drum – blog garden

97. The UUID can be obtained when the APP is installed for the first time as a machine identifier.

-(void) initMachineIdentifier { NSString* uuid=[[NSUserDefaults standardUserDefaults] objectForKey:@"__machine_UUID"]; If (uuid==nil){// Note the following uuid, which is obtained differently each time you run it. CFUUIDRef puuid = CFUUIDCreate( nil ); CFStringRef uuidString = CFUUIDCreateString( nil, puuid ); NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString)); CFRelease(puuid); CFRelease(uuidString); [[NSUserDefaults standardUserDefaults] setObject:result forKey:@"__machine_UUID"]; [[NSUserDefaults standardUserDefaults] synchronize]; }}Copy the code

96. Continuous pushviewcontroller

Today there was an error in pushing two VC’s in a row, and the code looks like this:

[rootNav pushViewController:vc1 animated:NO];
[rootNav pushViewController:vc2 animated:NO];
Copy the code

I’ll do it like this, normally, in viewWillAppear for Vc1

[rootNav pushViewController:vc1 animated:YES]; [[[RVC rac_signalForSelector:@selector(viewDidAppear:)] take:1] subscribeNext:^(id x){[rootNav pushViewController:vc animated:NO]; }];Copy the code

95. Dictionary deletion

NSMutableArray* toBeDeleteArr=[[NSMutableArray alloc] init];
NSMutableArray *allKeys = [[viewControllersDic allKeys] mutableCopy];
for(NSString* key in allKeys){
    UIViewController* v=[viewControllersDic objectForKey:key];
    if([v isEqual:vc]){
        [toBeDeleteArr addObject:key];
    }
}
[viewControllersDic removeObjectsForKeys:[toBeDeleteArr copy] ];
Copy the code

94. It is not possible to use the @3x photo directly for the sake of illustration. This will cause the display to fail on some machines.

msgImg = [[UIImage imageNamed:@”tabBar_msg@3x”] retain]; Photos cannot be displayed on ios8.0 on iPod touch due to using @3x photos directly. The normal thing to do, then, is to use a photo directly for each screen.

93.xcodebuild -showBuildSettings

View project configuration information.

Run the above command in the directory of *. Xcodeproj to output the configuration information of the entire project.

For example, I have to check the $(SRCROOT) what is actual representative directory, can run the following commands: xcodebuild – showBuildSettings | grep “SRC \ | PROJECT”

Output:

2015-04-01 22:27:33.217 XcodeBuild [824:21844] [MT] iPhoneSimulator: SimVerifier Returned: Error Domain=NSPOSIXErrorDomain Code=53 "Simulator verification failed." UserInfo=0x7fd45a915970 {NSLocalizedFailureReason=A connection to the simulator verification service could not be established., NSLocalizedRecoverySuggestion=Ensure that Xcode.app is installed on a volume with ownership enabled., Xcodebuild [824:21844] [MT] DeveloperPortal: Using the pre - existing current store at the URL (file:///Users/taivex2/Library/Developer/Xcode/DeveloperPortal%206.2.db). EXCLUDED_INSTALLSRC_SUBDIRECTORY_PATTERNS = .DS_Store .svn .git .hg CVS HEADERMAP_INCLUDES_PROJECT_HEADERS = YES PROJECT  = DZMedical PROJECT_DERIVED_FILE_DIR = /Users/taivex2/Library/Developer/Xcode/DerivedData/DZMedical-dhbntwylstigecfaaukpdvwlfitn/Build/Intermediates/DZMedical. Build /DerivedSources PROJECT_DIR = /Users/ taiVEX2 /Desktop/ YDYL_Pub PROJECT_FILE_PATH = /Users/ taiVEX2 /Desktop/ YDYL_Pub/ dzMedica. xcodeProj PROJECT_NAME = DZMedical PROJECT_TEMP_DIR = /Users/taivex2/Library/Developer/Xcode/DerivedData/DZMedical-dhbntwylstigecfaaukpdvwlfitn/Build/Intermediates/DZMedical. build PROJECT_TEMP_ROOT = /Users/taivex2/Library/Developer/Xcode/DerivedData/DZMedical-dhbntwylstigecfaaukpdvwlfitn/Build/Intermediates SRCROOT = /Users/ taiVEX2 /Desktop/ YDYL_Pub VERSION_INFO_STRING = "@(#)PROGRAM: DZMedical-"Copy the code

Ref: qiita.com/kitanoow/it…

92. DidReceiveRemoteNotification must deal with three of the following:

You app needs to handle all the possible push notification Delivery States: * Your app was just launched * Your app was just brought from background to foreground * Your app was already running in  the foreground You do not get to choose at delivery time what presentation method is used to present the push notification, that is encoded in the notification itself (optional alert, badge number, sound). But since you presumably are in control of both the app and the payload of the push notification, you can specify in the payload whether or not there was an alert view and message already presented to the user. Only in  the case of the app is already running in the foreground do you know that the user did not just launch your app through  an alert or regularly from the home screen. You can tell whether your app was just brought to the foreground or not in didReceiveRemoteNotification using this bit of code:Copy the code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{     
    if ( application.applicationState == UIApplicationStateActive )      
      // app was already in the foreground
       else       
    // app was just brought from background to foreground       
 }
Copy the code

When the application from the foreground to background, arrive when push notifications, users click on the notification to the application, then in didReceiveRemoteNotification UIApplication status to UIApplicationStateInActive

Stackoverflow.com/questions/5…

#include <openssl/asn1.h> file not found. #include <openssl/asn1.h

The solution: Solution: the Targets — – > Search Paths — — — — — – > the Header Search Paths, add “$(PROJECT_DIR)/MinHang/thridpart/AliSDK” AliSDK file directory

Data type changes at 90.64 bit.

In 32-bit systems: int: 32 bits LONG: 32 bits NSInteger: 32 bits pointer: 32 bits Float: 32 bits Double: 32 bits CGFloat: 32 bits In 64-bit systems: int: 32 bits long: 64-bit NSInteger: 64-bit pointer: 64-bit float: 32-bit double: 64-bit CGFloat: 64-bitCopy the code

Char (1 byte), short(2 bytes),int(4 bytes),float(4 bytes), and double(8 bytes) occupy the same number of bytes on both 32-bit and 64-bit systems.

Ref: chun. Tips/blog / 2014/1…

89. Tree view stack, root window:

Presenting View finds its root view (except window). Presenting View (root view) and Presenting View are placed together in UITransitionView for animation switch. 3) When the animation is completed, the presenting View (root view) is removed from the presenting view and the Presenting view is added to the Window.Copy the code

88. PresentViewController pop-up style.

SDetailImageViewController* v=[[SDetailImageViewController alloc] init];
UINavigationController* nav=[[UINavigationController alloc] initWithRootViewController:v];
v.baseData=[self.picArray objectAtIndex:tap.view.tag];
nav.modalTransitionStyle =UIModalTransitionStyleCrossDissolve;
[self presentViewController:nav animated:YES completion:nil];
Copy the code
You can set modalTransitionStyle of presenting VC by setting the modalTransitionStyle property of presenting VC, which is defined as follows: Typedef enum {UIModalTransitionStyleCoverVertical = 0, / / at the bottom of the slide to UIModalTransitionStyleFlipHorizontal, / / flip horizontal into UIModalTransitionStyleCrossDissolve, / / cross dissolve UIModalTransitionStylePartialCurl, / / flip} UIModalTransitionStyle; We can see that there are four styles available: slide in from the bottom, flip in horizontally, cross dissolve and turn the page. These four styles are not limited by the device, that is, iPhone or iPad will display transitions according to the style we specify.Copy the code

87. The following animation is invalid because the affineTransform is not keypath for the CAAnimation

CGAffineTransform transform = CGAffineTransformIdentity; Transform = CGAffineTransformScale(transform, 0.5, 0.5); CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"affineTransform"]; scaleAnim.fromValue = [NSValue valueWithCGAffineTransform:CGAffineTransformIdentity]; scaleAnim.toValue = [NSValue valueWithCGAffineTransform:transform]; scaleAnim.removedOnCompletion = YES; ScaleAnim. Duration = 0.5 f; scaleAnim.fillMode=kCAFillModeForwards; scaleAnim.autoreverses=NO; [layer addAnimation:scaleAnim forKey:nil];Copy the code
Technically, affineTransform is not a property of CALayer, and is documented as a "convenience
method" wrapper around the transform property, which is documented as animatable.

It's only really by objective-c's implicit conversion of keypaths to selectors that it appears
affineTransform behaves like a property when use (under most circumstances) in a keypath.
However, the CA libraries are setup to observe only certain keypaths, and that's not one of them :-)
Copy the code

Ref: stackoverflow.com/questions/1…

86.navigationController.navigationItem vs navigationItem

Don't confuse the self. The navigationItem and self. The navigationController. NavigationItem, The UINavigationItem itself is used to customize the ViewController's own appearence during navigation, NavigationItem is an extension of the UIViewController class about UINavigationControllerItem category, So when UIViewController is presented in UINavigationController, the navigationItem property has a value, and when UIViewController is presented in UINavigationController, it has a value of nilCopy the code
@interface UIViewController (UINavigationControllerItem) @property(nonatomic, readonly, retain)UINavigationItem * navigationItem; . @endCopy the code
The class UIViewController has a property navigationItem. This is true of all the subclasses too whether it is a UICollectionViewController, UITableViewController, UINavigationViewController or any custom subclass. When presented by a UINavigationController the nav controller will create this property and so each view controller gets its own navigationItem. If you do not present it from a navigation  controller then the navigationItem is nil. Now, with a UINavigationController you are more than likely using this as your initial view controller. Therefore, the navigation controller is NOT being presented by another navigation controller and its navigationItem property is nil. The navigation bar is slightly different as this is managed the other way around.Copy the code

Ref: stackoverflow.com/questions/1…

85. The “affine” in CGAffineTransform means that the two parallel lines in the layer remain parallel after the transformation, regardless of the value of the transformation matrix.

  1. PerformSelector: withObject can pass a parameter [actually can pass multiple parameters]

SEL action2 = @selector(action2:); [object performSelector:action2 withObject:data afterDelay:1.f]; NSMethodSignature* MSigture =[[self class] NSInvocation Invocation void viewDidLoad{// Get method signature * MSigture =[self class] instanceMethodSignatureForSelector:@selector(addTwoNum:with:)]; NSInvocation* invokation=[NSInvocation invocationWithMethodSignature:msigture]; // setSelector and target [invokation setSelector:@selector(addTwoNum:with:)]; [invokation setTarget:self]; NSNumber* a=@1; NSInteger b=2; [invokation setArgument:&a atIndex:2]; [invokation setArgument: &batIndex :3]; [invokation retainArguments]; [invokation invoke]; NSInteger returnValue; [invokation getReturnValue:&returnValue]; NSLog(@"return value is:%ld",returnValue); //[invokation performSelector:@selector(invoke) withObject:nil afterDelay:5]; } -(NSInteger)addTwoNum:(NSNumber*) num1 with:(NSInteger)num2{ NSLog(@"%@",[NSThread currentThread]); NSInteger ret=num1.integerValue+num2; NSLog(@"%ld",ret); return ret; }Copy the code

NSInvocation as an alternative to Object Selector – Green

83. The view’s frame, bounds, and Center properties are simply access methods. When you manipulate a view’s frame, you’re actually changing the frame in the CALayer below the view, and you can’t change the view’s frame independently of the layer.

Frame isn’t a very clear property for a view or layer. It’s a dummy property calculated from bounds, Position, and Transform, so when any of these values change, the frame changes. Conversely, changing the value of the frame also affects the values in between

82. Why does iOS provide two parallel hierarchies based on UIView and CALayer? Why not have a simple hierarchy for everything?

The reason for this is separation of responsibilities, which also avoids a lot of duplicate code. Events and user interaction are different in many ways on iOS and Mac OS. A multi-touch based user interface is fundamentally different from a mouse and keyboard based user interface. That’s why iOS has UIKit and UIView, but Mac OS has AppKit and NSView. They are similar in function, but there are significant differences in implementation.

Drawing, layout and animation, by contrast, are concepts similar to the Mac laptop and desktop series used on touch screens on iphones and ipads. By separating the logic of this function and applying it to an independent Core Animation framework, Apple can share the code between iOS and Mac OS, making it more convenient for Apple’s own OS development team and third-party developers to develop applications on both platforms.

81.”Prior to iOS 7, the device token was the same across all app installations on a given device. Different apps on your phone, whether Tap Tap Revenge or USA Today, would utilize the same address, i.e., device token, to route the push notification to you. The security credentials that you pair with a message would ensure it made it to the right app. On iOS 7, Apple has gone one step further and made sure that device tokens are now different in every single app install. This helps further protect users’ privacy by removing another phone-level identifier.”

Ref: stackoverflow.com/questions/1…

80.1. Layout of new user certificates

In certificate Manager, right-click to develop a certificate and export it. Right-click to push the certificate export. Find the corresponding provision file export in Xcode.

79.store weak reference object in array, dictionary. one more thing: IOS6 and OSX 10.8 Coughs a Better Solution:

[NSHashTable weakObjectsHashTable]
[NSPointerArray weakObjectsPointerArray]
[NSPointerArray pointerArrayWithOptions:]
Copy the code

These should give you containers that hold weak references (but note matt’s comments below). 1.NSValue

+ (NSValue *)valueWithNonretainedObject:(id)anObject

This method is useful if you want to add an object to a collection but don’t want the collection to create a strong reference to it. 2.There is a tricky way use block to do so:

typedef id (^WeakReference)(void);
WeakReference MakeWeakReference (id object) {
    __weak id weakref = object;
    return ^{ return weakref; };
}
id WeakReferenceNonretainedObjectValue (WeakReference ref) {
    if (ref == nil)
        return nil;
    else
        return ref ();
}
[arr addObject:MakeWeakReference(obj)];
id newobj = WeakReferenceNonretainedObjectValue([arr objectAtIndex:0]);
Copy the code

3.Use a custom WeakReference class that hold on a weak pointer to the value.

  • We use collection (NSArray, NSMutableArray, NSDictionary, NSMutableDictionary, NSSet, NSMutableSet) storage object when the strong reference (you can use the singleton collection of stored data try!), sometimes we don’t If so, what should I do?

  • The use of NSHashTable is completely similar to that of NSSet. The difference is that one of its initialization methods is weakObjectsHashTable, which is specially used to store weak reference objects and will not hold them. When the owner of that object disappears, the object will also disappear from the collection Humanization!

  • Here are some of its methods:

- (BOOL)containsObject:(id)anObject Returns a Boolean value that indicates whether the hash table contains a given object. Returns a bool indicating whether the hash table contains the given object. - (void)addObject:(id)object Adds a given object to the hash table. - (void)removeObject (ID)object a given object from the hash table. WeakObjectsHashTable Returns a new hash table for storing weak references to its contents. + (ID)weakObjectsHashTable Returns a new hash table for storing weak references to its contents. Returns a hash table to store weakly referenced objects.Copy the code

Stackoverflow.com/questions/2…

78. Correct array deletion:

NSMutableArray *discardedItems = [NSMutableArray array]; SomeObjectClass *item; for (item in originalArrayOfItems) { if ([item shouldBeDiscarded]) [discardedItems addObject:item]; / / when traversing cannot be deleted, or you will not traverse} [originalArrayOfItems removeObjectsInArray: discardedItems];Copy the code

Ref: stackoverflow.com/questions/1… You can use the following code

for (int i=0;i<[inputArray count]; i++) {
        NSString *item = [inputArray objectAtIndex:i];
        if ([item rangeOfString:s].location == NSNotFound) {
            [inputArray removeObject:item];
            i--;
        }
    }
Copy the code

77. Type judgment

-(BOOL)isKindOfClass:class-object // Determines whether the object is an instance of class-object or its subclasses +(BOOL)isSubclassOfClass:class-object // isSubclassOfClass:class-objectCopy the code

76. Crashlogs can be parsed directly in Xcode

In the Xcode menu Window -- Organizer, go to the device Logs TAB for the crash log. Wait a moment and you'll see that the crash log has been resolved automatically (most of the time it will be resolved automatically). Don't use Symbolicatecrash to parse crash logsCopy the code

75. Get represented

appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
Copy the code

74.sqlite does not support SELECT INTO.

You can probably use this form instead:
INSERT INTO equipments_backup  SELECT * FROM equipments;

CREATE TABLE equipments_backup AS SELECT * FROM equipments

INSERT INTO destinationTable (risposta, data_ins)
SELECT STATUS risposta, DATETIME('now') data_ins
FROM   sourceTable
Copy the code

73. Scroll to the bottom line of UITableView:

Method one: / / the following statements use can lead to a collapse in simulator [table setContentOffset: CGPointMake (0, CGFloat. Max)] method 2: if (self.messages.count > 0) [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; Method 3: //Works with autolayout, BUT it's important to call this method from viewDidLayoutSubviews -(void)scrollToBottom{ CGFloat yOffset = 0; if (self.tableView.contentSize.height > self.tableView.bounds.size.height) { yOffset = self.tableView.contentSize.height  - self.tableView.bounds.size.height; } [self.tableView setContentOffset:CGPointMake(0, yOffset) animated:NO]; }Copy the code

Stackoverflow.com/questions/2…

72. Array filtering:

@interface Food : NSObject
@property (nonatomic, strong) NSString *foodName;
@property (nonatomic, assign) NSInteger idFood;
@end
@implementation Food
@end
Food *food1 = [[Food alloc]init];
Food *food2 = [[Food alloc] init];
food1.foodName=@"aaaa"; food1.idFood=1;
food2.foodName=@"bbbb"; food2.idFood=2;
NSArray *array = [NSArray arrayWithObjects:food1, food2, nil];
[array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Food* evaluatedObject, NSDictionary *bindings){
    if(evaluatedObject.idFood>1)
        return YES;
    return NO;
}]];
Copy the code
NSLog(@"foodname:% @foodid :%d",[(Food*)array[0] foodname],[(Food*)array[0] idFood]);Copy the code

71.awakeFromNib

-(id) initWithCoder:(NSCoder *)aDecoder // an initialization method that is called before the nib component is loaded. Nil. -awakeFromNib // In this method, each component in the NIB has been loaded and information about the component can be retrieved.Copy the code

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

ios – Should I be using awakeFromNib or initWithCoder here? – Stack Overflow

70. About JSON in OC

An object that may be converted to JSON must have the following properties:// But the converted object must have the following properties: The top level object is an NSArray or NSDictionary.// The top level object must be NSArray or NSDictionary All objects are instances of NSString, NSNumber, NSArray, NSDictionary, // All objects must be instances of NSString, NSNumber, NSArray, NSDictionary, and NSNull // All NSDictionary keys must be NSString Numbers are not NaN or infinity.// The number object cannot be non-numeric or infinite NSArray or NSDictionary converts a string to a JSON object: NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}"; NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];Copy the code

69. Parallel queues :GCD doesn’t guarantee that subsequent blocks on the same queue are invoked on the same thread

66. PredicateWithFormat use of ANY. For handling one-to-many relationships, such as a class containing an array of objects.

For the array of the following structure, if we want to filter Name,

I would like to create a NSPredicate searching if a given string is contained inside of Name. How can I achieve reaching  that deep? If you cant understand the graph. I have an array full of dictionaries, Inside the dictionaries are A string, An Array of dictionaries, and An Array of dictionaries, Inside of the dictionaries are string objects So How do I get into the second dictionaries and search the Name key NSString *str = <search string>; NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY Mens.Name LIKE %@ OR ANY Womens.Name LIKE %@", str, str]; NSArray *result = [your_array filteredArrayUsingPredicate:pred]; BOOL success = result.count > 0;Copy the code

Ref:stackoverflow.com/questions/2…

65.weak vs assign :

1. Weak set to nil when the object is destroyed. Use the following code carefully in MRC:

if (self.delegate && [self.delegate respondsToSelector:@selector(test:)]) {
    [self.delegate test:nil];
}
Copy the code

www.cnblogs.com/jamesy/p/39…

For ARC projects I would use strong instead of retain, I would use assign for C primitive properties and weak for weak references to Objective-C objects.

64. The constraint

UIViewAutoresizingNone is not automatically adjusted. UIViewAutoresizingFlexibleLeftMargin distance at the left of the automatic adjustment and superView, assurance and superView the right distance remains the same. UIViewAutoresizingFlexibleRightMargin automatic adjustment and the right of the superView distance, which can guarantee the distance with superView left unchanged. UIViewAutoresizingFlexibleTopMargin automatic adjustment and the distance from the top superView, guarantee and the distance from the bottom of the superView remains the same. UIViewAutoresizingFlexibleBottomMargin automatic adjustment and superView at the bottom of the distance, that is to say, and on top of the superView distance remains the same. UIViewAutoresizingFlexibleWidth automatically adjust the width of the assurance and superView the left and the right distance remains the same. UIViewAutoresizingFlexibleHeight automatically adjust height, guarantee and the distance from the top and bottom superView remains the same. UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin automatic adjustment and superView on the left side of the distance, Make sure the distance to the left and the distance to the right is proportional to the original distance to the left and the right. For example, the original distance is 20,30, and the adjusted distance should be 68,102. UIView* av=[[UIView alloc] initWithFrame:CGRectMake(10, 20, 80, 40)]; UIView* av=[[UIView alloc] initWithFrame:CGRectMake(10, 20, 80, 40)] / / and the right distance 70 av autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; // When the superView width is 320 NSLog(@"%@",NSStringFromCGRect(av.frame)); UIView* av=[[UIView alloc] initWithFrame:CGRectMake(10, 20) UIView* av=[[UIView alloc] initWithFrame:CGRectMake(10, 20, 80, 40)]; / / and the right distance 70 left from 10. Av autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; // When the superView width is 320 NSLog(@"%@",NSStringFromCGRect(av.frame)); / / {{30, 20}, {80, 40}} / / and the right distance left from 30, 210 and above is proportional to the {{170} 20, 40} {80}Copy the code

63. Instancetype can return objects of the same type as the method class

Instancetype can return objects of the same type as the method’s class. Id can only return objects of unknown type. ② InstanceType can only be used as a return value, not as a related result type, as id can be used as a return value. Class methods that start with alloc or new. Instance methods that start with autorelease, init, retain, or self return an object of the class type of the method. These methods are called associated return types. Although the above method returns the id type, but because they are associated return types, the compiler do the corresponding type checking [[[NSArray alloc] init] mediaPlaybackAllowsAirPlay]; // “No visible @interface for NSArray declares the selector mediaPlaybackAllowsAirPlay” [[NSArray array] mediaPlaybackAllowsAirPlay]; // (No error), this is not the correlation return type, then instanceType is useful.

Instancetype and ID keywords in Objective-C

62. PerformSelectorOnMainThread and dispatch_async on main queue

PerformSelectorOnMainThread needs specific run loop mode dispatch_async on main queue from the run loop mode. By default, -performSelectorOnMainThread:withObject:waitUntilDone: only schedules the selector to run in the default run loop mode. If the run loop is in another mode (e.g. the tracking mode), it won’t run until the run loop switches back to the default mode. You can get around this with the variant -performSelectorOnMainThread:withObject:waitUntilDone:modes: (by passing all the modes you want it to run in).

On the other hand, dispatch_async(dispatch_get_main_queue(), ^{ … }) will run the block as soon as the main run loop returns control flow back to the event loop. It doesn’t care about modes. So if you don’t want to care about modes either, dispatch_async() may be the better way to go.

Ref: stackoverflow.com/questions/9…

61. Difference between dispatch_async and dispatch_sync on serial queue

A. The difference between them is synchronous or asynchronous, relative to the queue that currently appending tasks to our queue. Sync blocks and waits; Asynchronously returns immediately without waiting. C. To summarize, if you want to operate between tasks, you control whether queues are parallel or serial, and if you want to operate relative to the current thread, you control whether dispatch_async or dispatch_sync. Yes. Using serial queue ensure the serial execution of tasks. The only difference is that dispatch_sync only return after the block is finished whereas dispatch_async return after it is added to the queue and may not finished. for this code

dispatch_async(_serialQueue, ^{ printf("1"); });
printf("2");
dispatch_async(_serialQueue, ^{ printf("3"); });
printf("4");
it may print 2413 or 2143 or 1234 but 1 always before 3
for this code
dispatch_sync(_serialQueue, ^{ printf("1"); });
printf("2");
dispatch_sync(_serialQueue, ^{ printf("3"); });
printf("4");
it always print 1234
Copy the code

Ref:stackoverflow.com/questions/1… GCD learning (6) Dispatch_async and dispatch_sync

60. Dispatch_set_target_queue

  • He can change the priority of the queue to be the same as the target queue
  • If multiple serial queues are assigned to the same destination using dispatch_set_target_queue, then the serial queues are executed synchronously on the destination queue rather than in parallel.
-(void)testTargetQueue {
    dispatch_queue_t targetQueue = dispatch_queue_create("test.target.queue", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue1 = dispatch_queue_create("test.1", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue2 = dispatch_queue_create("test.2", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue3 = dispatch_queue_create("test.3", DISPATCH_QUEUE_SERIAL);
    dispatch_set_target_queue(queue1, targetQueue);
    dispatch_set_target_queue(queue2, targetQueue);
    dispatch_set_target_queue(queue3, targetQueue);
    dispatch_async(queue1, ^{
        NSLog(@"1 in:%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:3.f];
        NSLog(@"1 out");
    });
    dispatch_async(queue2, ^{
        NSLog(@"2 in:%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:2.f];
        NSLog(@"2 out");
    });
    dispatch_async(queue3, ^{
        NSLog(@"3 in:%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:1.f];
        NSLog(@"3 out");
    });
}
Copy the code

Output:

982 TEST_TabCrash[17918:50312] 1 in:<NSThread: 0x7ff439f39040>{number = 2, Name = (null)} 2015-10-31 09:59:56.986 TEST_TabCrash[17918:50312] 1 out 2015-10-31 09:59:56.987 TEST_TabCrash[17918:50312] 2 in:<NSThread: 0x7ff439f39040>{number = 2, Name = (null)} 2015-10-31 09:59:58.989 TEST_TabCrash[17918:50312] 2 out 2015-10-31 09:59:58.989 TEST_TabCrash[17918:50312] 3 in:<NSThread: 0x7ff439f39040>{number = 2, Name = (null)} 2015-10-31 09:59:59.991 TEST_TabCrash[17918:50312 Note that the above code for queue1,queue2,queue3 is treated on the thread corresponding to targetQueueCopy the code

3. If the target queue is assigned the same priority as the global queue by dispatch_set_target_queue, the global queue is assigned the same priority. Similar nsoperation []

Dispatch Queue Targeting All custom dispatch queues have the concept of a target queue. In essence, a custom dispatch queue doesn’t actually execute any work, but passes work to its target queue for execution. Normally the target queue of a custom queue is the default-priority global queue. The target queue of a custom queue can be set by using the dispatch_set_target_queue function. You can pass it any other dispatch queue, even another custom queue, so long as you never create a cycle. This function can be used to set the priority of a custom queue by simply setting its target queue to a different global queue. If you set your custom queue’s target to be the low priority global queue, all work on your custom queue will execute with low priority, and the same with the high priority global queue. Another potential use of this is to target a custom queue to the main queue. This will cause all blocks submitted to that custom queue to run on the main thread. The advantage of doing this instead of simply using the main queue directly is that your custom queue can be independently suspended and resumed, and could potentially be retargeted onto a global queue afterwards, although you’ll have to be careful to ensure that all blocks which run after that point can tolerate being away from the main thread! Yet another potential use is to target custom queues to other custom queues. This will force multiple queues to be serialized with respect to each other, and essentially creates a group of queues which can all be suspended and resumed together by suspending/resuming the queue that they target. For a way that this could be used, imagine an application which is scanning a set of directories and loading the files within. In order to avoid disk contention, you want to make sure that only one file loading task is active for each physical disk. However, multiple files can be read from physically separate disks simultaneously. To make this happen, all you have to do is build a dispatch queue structure which mirrors your disk structure.

First, you would scan the system and find the disks, and create a custom dispatch queue for each one. Then you would scan the filesystems and create a custom queue for each one of those as well, pointing their target queues at the queue of the appropriate disk. Finally, each directory scanner can have its own queue as well, pointing the target at the filesystem on which the directory resides. The directory scanners can enumerate their directories and submit a block for each file directly to their own queue. Due to how the system is set up, this will inherently serialize all access to each physical disk while allowing parallel access to separate disks, all without any manual intervention beyond the initial queue setup process.

Ref: usage of dispatch_set_target_queue

60. Why is dispatch_get_current_queue abandoned

dispatch_get_current_queue never really made sense in the first place. Here’s why: There are a handful of “root” queues (one for each priority, and then the main queue). Every other queue ultimately ends up targeting one of these root queues. This means that, in the general case, there isn’t a single answer to the question, “What queue am I running on?” For instance, if you have queue B that targets queue A, then either A or B would be a reasonable answer to that question, for a block submitted to queue B. Furthermore, since all queues end up targeting one of the global/root queues, arguably the best answer would be “whatever root queue it ended up executing on”, except that’s not really useful to anyone, because it doesn’t significantly differentiate anything. In my experience, in most cases, what folks want from dispatch_get_current_queue is the answer to, “What queue was I initially submitted to?” However, by definition, whatever code submitted the block already knows what queue it was submitted to (because it’s doing the submission). So arguably, if you needed to capture that information, you could trivially do so at enqueue time; you don’t need dispatch_get_current_queue to answer that question. For these cases, dispatch_get_current_queue would just be a shortcut, and a flawed one at that (because of queue targeting.) The other big class of cases is when you want to know if you’re on the main queue. -[NSThread isMainThread] is sufficient/authoritative for that, so you don’t need dispatch_get_current_queuefor that either.

Another answerer also pointed out that dispatch_get_current_queue was frequently misused in an attempt to emulate recursive locking with GCD queues. It’s not possible to reliably implement recursive locks in a queue based system because “queues aren’t locks”. I’ve written at some length about that particular situation in another answer.

59. In.mm files, that is, files compiled in Objective-C ++ :

This will cause a compilation error:

RAC(self.submitButton, enabled) = [RACSignal
combineLatest:@[siteAddressValidSignal, accessKeyValidSignal]
reduce:^id(NSNumber *siteAddressValid, NSNumber *accessKeyValid){
    return @(siteAddressValid.boolValue && accessKeyValid.boolValue);
}];
Copy the code

It has to be like this:

  [RACSignal  combineLatest:@[siteAddressValidSignal, accessKeyValidSignal] reduce:(id)^id(NSNumber *siteAddressValid, NSNumber *accessKeyValid){         return @(siteAddressValid.boolValue && accessKeyValid.boolValue); }];
  [RACSignal combineLatest:reduce:] won't compile as Objective-C++
Copy the code

58.[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone]; // Instead of using the default tableView delimiter, use your own delimiter.

In each cell, you can customize what the dividing line looks like by using a thin label and placing it in place

UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(sparatorStartx, cellHeight-0.5, cellWidth, 0.5)]; [line1 setBackgroundColor:[UIColor lightGrayColor]]; [cell.contentView addSubview:line1]; If (indexPath. Row == 0){UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size. Width, 0.5)]; [line1 setBackgroundColor:[UIColor lightGrayColor]]; [cell.contentView addSubview:line1]; }Copy the code

Note: each cell can only add a subview once, so the above method is only to explain how to add

[rootdir] [rootdir] [rootdir] [rootdir] [rootdir]

The blue ones are folders, and the yellow ones are

NSString *earth = [[NSBundle mainBundle] pathForResource:@"Brad Cox" ofType:@"png"];

When using folders, use the same method, you need to specify the folder path

{
    NSString *earth = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"png" inDirectory:@"bb"];
    NSLog(@"%@",earth);
}
{
    NSString *earth = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"png" ];
    NSLog(@"%@",earth);
}
Copy the code

Output:

The 2016-07-09 22:31:21. 072 testaa (20822-74824) /Users/taivex2/Library/Developer/CoreSimulator/Devices/6F5EE523-D3D1-4F69-AD19-F0DD311A5F0C/data/Containers/Bundle/Appli Cation / 6 ffab630-2 b87-49 c9 - B988-19 f5a195ab0f/testaa app/bb/Amy polumbo ng 22:31:21 2016-07-09. 072 testaa (20822-74824) /Users/taivex2/Library/Developer/CoreSimulator/Devices/6F5EE523-D3D1-4F69-AD19-F0DD311A5F0C/data/Containers/Bundle/Appli cation/6FFAB630-2B87-49C9-B988-19F5A195AB0F/testaa.app/a.pngCopy the code

Use NSBundle. Note the difference between mainBundle and Custom Bundle

56. Get AppDelegate

appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

Stackoverflow.com/questions/1…

55.If you have an NSArray of strings

{ @"ONE", @"ONE", @"ONE", "TWO", @"THREE", @"THREE" }

How would I turn that into

{ @”ONE”, @”TWO”, @”THREE” }

My initial thought was that you could do:

NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSLog(@"%@", [a valueForKeyPath:@"@distinctUnionOfObjects.self"]);
//But that does not maintain order. Therefore, you have to do it manually:
NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSMutableArray * unique = [NSMutableArray array];
NSMutableSet * processed = [NSMutableSet set];
for (NSString * string in a) {
  if ([processed containsObject:string] == NO) {
    [unique addObject:string];
    [processed addObject:string];
  }}
Copy the code

I use an NSMutableSet for determining if I’ve already come across this entry before (as opposed to [unique containsObject:string], since a set will have O(1) lookup time, and an array has O(n) lookup time. If you’re only dealing with a small number of objects, then this won’t matter. However, if the source array is very large, then using the set to determine uniqueness may add a bit of a speed boost. (however, you should use Instruments to profile your code and see if it’s necessary)

NSArray * uniqueArray = [[NSOrderedSet orderedSetWithArray:duplicatesArray] array];
This way, you also preserve the order!
NSArray *myArray = @[@"TWO", @"THREE",@"ONE", @"ONE", @"ONE", @"THREE"];
NSArray * uniqueArray = [[myArray valueForKeyPath:@"@distinctUnionOfObjects.self"] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
Copy the code

Stackoverflow.com/questions/4…

54. For AFNetworking 2.0 – “Unacceptable Content-Type: Text /plain”

Solution: manager. ResponseSerializer. AcceptableContentTypes = [NSSet setWithObject: @ “text/plain”]. Stackoverflow.com/questions/2…

53. The timestamp from the server is best represented by a long long value:

NSLog(@”%lld”, [myValue longlongValue]);

52. All strings in sqllite are encoded in Unicode

In Microsoft SQL Server, VARCHAR is ASCII and NVARCHAR is Unicode (UTF-16). In SQLite, all text is Unicode, so it’s not relevant. In any case, SQLite is loosely typed so it wouldn’t make a difference anyways. See www.sqlite.org/datatype3.h…:) Moreover SQLite will never enforce length specifications. If you declare a column as CHAR(n), VARCHAR(n), TEXT or STRING or (…) it has no length limitation. – Benoit Oct 14 ’10 at 6:22

Stackoverflow.com/questions/3…

51.NSRecursiveLock

According to the official documentation, this lock prevents a deadlock caused by a thread applying for the lock more than once. When a thread applies for a lock (once or more) on a piece of code, the other thread attempts to apply again will not succeed and will block. A lock defined by the NSRecursiveLock class can be locked multiple times on the same thread without causing a deadlock. A recursive lock keeps track of how many times it is locked. Each successful lock must balance calls to unlock. Only when all lock and unlock operations are balanced is the lock actually released to other threads. The same thread, the same thread, locks the same lock multiple times without unlock, so NSRecursiveLock is needed to avoid deadlocks

Different ways to implement locking in Objective-C

50. Notice the meaning of descending in the return value. If NSOrderedDescending means that from S to V is in descending order, then S is bigger than V

NSString* s=@"12345a";
NSString* v=@"12345b";
if([s compare:v options:NSCaseInsensitiveSearch]==NSOrderedDescending){
    NSLog(@"%@ is bigger than %@",s,v);
}else{
    NSLog(@"%@ is smaller than %@",s,v);
}
Copy the code

Output :12345a is smaller than 12345b

49. Added the impact of issuing certificates

If the original distribution certificate is invalid and I create a new one in the developer background, what are the certificates and do I need to change them accordingly? To add a distribution certificate to the developer center, a distribution Provisioning File and an AD Provisioning file need to be regenerated because the original two certificates are not related to the newly added distribution certificate. That is, both certificates are associated with development certificates. The push certificate for the production version does not need to be changed because the push certificate is associated with the AppID.

48. The application does not have a valid signature

In Xcode -> Product -> Clean, clean up the solution, and in general, that should solve the problem.

47.AD Hoc mode validation of production certificates

The Production SSL Certificate is generated in the developer center and imported into the MAC, and then the Developer Center is generated to create an Ad Hoc Provisioning Profiles. After these are done, go to XCode->Product->Archive. You can see the packaged file in the Organizer, and Export gets the IPA file. The push of the production certificate can be verified by installing it on authorized devices through iTunes.

To summarize, the first step is to enable push in the Apple Developer Center, and then publish the certificate + Ad Hoc Provisioning file + Push production certificate. Through Ad Hoc mode, the live network Push service can be verified. The steps of iTunes installation: first add the generated IPA file to the database, and then the list of applications will appear the corresponding APP, click install, and then synchronize, you can install to the iPhone

46.NSDate creation using NSCalendar and NSTimeZone

If you are creating a date manually you should specify the calendar (2012 in Gregorian, but 5772 in Hebrew) and time zone (22PM London time, but 7AM Sydney time).

// Use the user's current calendar and time zone
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone: [NSTimeZone systemTimeZone]];

// Specify the date components manually (year, month, day, hour, minutes, etc.)
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setHour:22];
[timeZoneComps setMinute:0];
[timeZoneComps setSecond:0];
// ... year, month, ...

// transform the date compoments into a date, based on current calendar settings
NSDate *date = [calendar dateFromComponents:timeZoneComps];
Copy the code

45. Today, I ran an old app in ios7 and found an exception Xib not found. The solution is: access Interface Builder, find the corresponding Xib, click localize and add the corresponding localization information.

Stackoverflow.com/questions/1…

  1. LocalTimeZone represents the time zone in use by the current program

localTimeZone VS systemTimeZone

  • localTimeZone is the default time zone for the current application. This can be set by the user or programmatically in the app (or possibly in other ways). It’s basically a pointer to defaultTimeZone with a level of indirection; if the default time zone changes, localTimeZone will change as well.
  • systemTimeZone, on the other hand, is the time zone used by the core system. A cached value for this will not change if the system time zone changes during the application’s execution, unlike localTimeZone.
  • If you want to know the system’s time zone setting, you probably want to use +[NSTimeZone systemTimeZone]. If you just want the correct time zone for your app to work in, you probably want +[NSTimeZone localTimeZone].

Stackoverflow.com/questions/1…

43. Note that the MM in format is large and that HH is uppercase.

[NSDate date] returns the date in GMT. If you want to output the time in the current time zone: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.timeZone=[NSTimeZone localTimeZone]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //[dateFormatter setDateFormat:@" YYYY-MM-DD hh: MM :ss"]; NSString *dateString = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"str:[%@]",dateString);Copy the code

42. Failed to find application’s “aps-environment” rights string when pushing

did Fail To Register For Remote Notifications With Error: ErrorDomain =NSCocoaErrorDomain Code=3000 “Application’s” aps-environment “rights not found string” UserInfo= 0x15D68990 {NSLocalizedDescription= Application ‘aps-environment’ right string}

Answer: There are two reasons for this problem. One is because the boundle Identifier of the current application is different from the corresponding Boundle Identifier in the push certificate, and the other is due to provision You can go to the developer center to generate a provision profile containing the deviceToken for debugging devices. Then download it, double click, install it into Xcode and recompile it. Or maybe your Provisioning Profile doesn’t have APNS. Please go to the Apple Developer website to set up the certificate, update the Provisioning Profile, and re-import Xcode.

41.NSString case conversion

NSString becomes uppercase, lowercase, uppercase at the beginning of each letter

-(void)viewDidLoad{ NSString *a = @"i like long dress"; NSLog(@" \n uppercase a:%@ ", [a uppercaseString]); NSLog(@" \n lowercase a:%@ ", [a lowercaseString]); NSLog(@" \n capital a:%@ ", [a capitalizedString]); } 2011-07-11 17:33:58.082 Q[6111:207] a:I LIKE a LONG DRESS Q[6111:207] A :I Like Long DressCopy the code

40. # import # include

They’re about the same. Only # import solves the problem of double references. However, using # include requires careful handling of reread references.

"What is the difference between #include and #import? #import ensures that the preprocessor only includes a file once. #include will allow you to include the same file many Times. "Excerpt from: Hillegass, Aaron." Objective-C Programming: The Big Nerd Ranch Guide, 2/ E (Big Nerd Ranch Guides)."Copy the code

Import vs. @class vs. include

39. Call back when CAAnimition is completed

The following methods are valid only if the following Settings are set

CAAnimation *anim = ... anim.removedOnCompletion = NO; // If this is YES, then the callback will also be called. CATransition *animation = [CATransition animation]; [animation setType:kCATransitionFade]; [animation setSubtype:kCATransitionFromTop]; [animation setDelegate:self]; - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{ }Copy the code

CAAnimation Completion handler

38.CAAnimationGroup overrides the Settings of other animations in the composite animation

CAAnimationGroup *anim = [CAAnimationGroup animation]; [anim setAnimations:[NSArray arrayWithObjects:[self transparencyAnimation], [self translateAnimation], nil]]; [anim setDuration: 3.0]; / / this time period, will cover other animation cycle [anim setRemovedOnCompletion: NO]; // This will also override [anim setDelegate:self]; / / this will also cover [anim setFillMode: kCAFillModeForwards]; // This will also [layer addAnimation:anim forKey:nil]; "... animations are clipped to the duration of the animation group. For example, a 10 second animation grouped within an animation group with a duration of 5 seconds will only display the first 5 Seconds of the animation. The delegate and removedOnCompletion properties of animations in the animations property are The CAAnimationGroup delegate does receive these messages."Copy the code

The use of the CAAnimationGroup

37. Side to side shaking effect

CAKeyframeAnimation * anim = [ CAKeyframeAnimation animationWithKeyPath:@"transform" ] ; Anim. Values = @ [[NSValue valueWithCATransform3D: CATransform3DMakeTranslation (0.0 5.0 f, f, 0.0 f)]. [NSValue valueWithCATransform3D: CATransform3DMakeTranslation (5.0 f, f 0.0, 0.0 f)]]. anim.autoreverses = YES ; Anim. RepeatCount = 2.0 f; Anim. speed = 2 anim.duration = 0.07f; [ viewToShake.layer addAnimation:anim forKey:nil ] ;Copy the code

Effect of CAAnimation tip

36 stringByAddingPercentEscapesUsingEncoding not special characters! * ‘(); : @ & = + $, /? %#[] encodes

stringByAddingPercentEscapesUsingEncoding will convert the Unicode* character to the percent escape format. Note: stringByAddingPercentEscapesUsingEncoding not special characters! * ‘(); : @ & = + $, /? Code # % [], if you have these special characters in your url parameters, will use the following CFURLCreateStringByAddingPercentEscapes said

stringByReplacingPercentEscapesUsingEncoding will do the opposite, convert the percent escape to the Unicode*.

The urlEncode objectiveC

35. NSIndexPath in UITableView starts from zero.

34.[UITableView cellForRowAtIndexPath:] Can only get visible cells, if not, return nil

An object representing a cell of the table or nil if the cell is not visible or indexPath is out of range. So if that cell is not currently visible then it will return nil. So, is it visible?

Other than that – check that you are actually creating cells in cellForRowAtIndexPath: as you haven’t specifically shown that you are.

33. StringByAddingPercentEscapesUsingEncoding urlEncode the connection string

NSString *strUrl1 = [NSString stringWithFormat:@"%@%@?Token=%@&taskid=%d&sn=%@&remindtime=%@&inputuser=%@&delflag=%@&lastmodifydate=%@",k3BaseURL,kAct ionUpdateDrugRemindTime,Token,intId,sn,remindtime,inputuser,@"0",lastmodifydate]; self.alertID=[NSString stringWithFormat:@"%d",intId]; strUrl1 = [strUrl1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - (NSString *)URLDecode{ NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "]; result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; return result; }Copy the code

UIScrollView scrolls horizontally to set the state of the UIPageControl page number based on the current contentoffset. x value. Note that ceil and floor are used for approximations below, depending on the scrolling direction.

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGFloat pageWidth = self.view.frame.size.width; int page=0; / / set the values in different ways according to the rolling direction if (lastContentOffset > scrollView. ContentOffset. X) {page = (int) (ceil (scrollView. ContentOffset. / x pageWidth)); } else if(lastContentOffset<scrollView.contentOffset.x){ page =(int)(floor(scrollView.contentOffset.x / pageWidth)); } lastContentOffset=scrollView.contentOffset.x; pageIndicator.currentPage=page; }Copy the code

31. Color manipulation of indicator points in UIPageControl.

  • PageIndicatorTintColor No selected spot color
  • CurrentPageIndicatorTintColor color the current page number value

30. The difference between several mathematical functions for approximating values

Ceil (x) returns the smallest integer value not less than x (which is then converted to double). Floor (x) returns the maximum integer value not greater than x. Round (x) returns the rounded integer value of x.Copy the code

29. In IOS6, the file name must be case-sensitive, otherwise the corresponding file will not be found

So let's say there's a file default1.png in the bundle and it says: in IOS7 or older, you can load the file, but in ios6.x,image1 is just nil UIImage *image1 = [UIImage imageNamed:@"Default1"];Copy the code

28. Disable vertical scrolling in UIScrollView, only horizontal scrolling is allowed

Scrollview. contentSize = CGSizeMake(your desired length, 0); Disallow horizontal scrolling of UIScrollView, only vertical scrolling of scrollView. contentSize = CGSizeMake(0, width you want);Copy the code

27. Hiding the status Bar in ios

For iOS6 and below, we used to write a line of code in didFinishLaunchingWithOptions: as [UIApplication sharedApplication].statusBarHidden = YES;

26.UIScrollView scroll direction

//somewhere in the header
@property (nonatomic, assign) CGFloat lastContentOffset
//
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    ScrollDirection scrollDirection;
    if (self.lastContentOffset > scrollView.contentOffset.x)
        scrollDirection = ScrollDirectionRight;
    else if (self.lastContentOffset < scrollView.contentOffset.x)
        scrollDirection = ScrollDirectionLeft;
    self.lastContentOffset = scrollView.contentOffset.x;
    // do whatever you need to with scrollDirection here.
}
Copy the code

24. When viewWillAppear: is triggered, the corresponding View Controller becomes active

ViewWillAppear: The function of the viewWillAppear method is to interact with the changing content on the screen. Tell the View Controller to display the corresponding interface content to the front of the screen: make sure that all text controls in the View Controller display the latest information, that necessary data is accessible, and that appropriate notifications are observed. When viewWillAppear: is triggered, the corresponding View Controller becomes active

23.// Replace the width in img in the HTML text with 90% so that it fits each screen

-(NSString*)replaceImgTagWidth:(NSString*)markup{ NSString *regexToReplaceWidth = @"<(img)\\s+src=\"(.*?) \ ". *? > "; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceWidth options:NSRegularExpressionCaseInsensitive error:&error]; return [regex stringByReplacingMatchesInString:markup options:0 range:NSMakeRange(0, markup.length) withTemplate:@"<img src=\"$2\" style=\" width:92%;border: 0px; margin:0px; padding: 0px; font-size: 0px; color: transparent;\" />"]; }Copy the code

[000] Regex summary in IOS

22. Nsstrings traversal

- (NSString *)replaceChineseQuatationMark:(NSString*) markup{ NSMutableString* s=[markup mutableCopy]; Unichar temp = [@ "" "characterAtIndex: 0]; NSInteger len=s.length; BOOL flag=NO; for(NSInteger i=0; i<len; i++){ if([s characterAtIndex:i]=='<'){ flag=YES; continue; } if([s characterAtIndex:i]==temp && flag==YES) { [s replaceCharactersInRange:NSMakeRange(i, 1) withString:@"\""]; continue; } if([s characterAtIndex:i]=='>') flag=NO; } return [s copy]; }Copy the code

21. Customize the UITableViewCell separator line.

    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
after that
    #define cellHeight 80 // You can change according to your req.
    #define cellWidth 320 // You can change according to your req.

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seprater_line.png"]];
        imgView.frame = CGRectMake(0, cellHeight, cellWidth, 1);
        [customCell.contentView addSubview:imgView];
        return customCell;
    }
Copy the code

20. The implementation of a block involves three constructs

Struct __main_block_impl_0 {struct __block_impl impl; Struct __main_block_desc_0 * Desc; struct __main_block_desc_0 * Desc; Struct __Block_byref_val_0 struct __Block_byref_val_0 struct __Block_byref_val_0 Static struct __main_block_desc_0 {// Static struct __main_block_desc_0 {// Static struct __main_block_desc_0 { unsigned long reserved; unsigned long Block_size; void (*copy )(struct __main_block_impl_0*, struct __main_block_impl_0*); void (*dispose )(struct __main_block_impl_0*); } struct __Block_byref_val_0 { void *__isa ; __Block_byref_val_0 *__forwarding ; int __flags ; int __size ; int val ; };Copy the code

19. Frame is not a very clear property for a view or layer. It is a dummy property calculated from the bounds, Position, and Transform, so when any of these values change, the frame changes. Conversely, changing the value of the frame also affects the values in between

18. Usage of correlation attributes

#import <objc/runtime.h>
static char alertInfoKey;
@implementation ViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    NSString* dataYouWantToPass = @"some info";
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"hello" message:@"miss-chalk" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"YES", nil];
    [alert show];
    objc_setAssociatedObject(alert, &alertInfoKey, dataYouWantToPass, OBJC_ASSOCIATION_RETAIN);
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString* data = objc_getAssociatedObject(alertView, &alertInfoKey);
    NSLog(@"%@",data);
}
@end
Copy the code

17. For a block that references an external variable, if it is not copied, it will only be scoped to the stack in which it was declared (type __NSStackBlock__). Xcode will cause a compilation error if it attempts to return such a block in a non-ARC context. So in non-ARC situations, blocks must be copied to the heap to be used outside of functions.

www.mgenware.com/blog/?p=503

16. Different usage of frame and bounds

frame
    The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
bounds
    The bounds rectangle, which describes the view’s location and size in its own coordinate system.
    So if you want to change the position of your cell within it’s superview (the tableview in this case), use the frame. Bu if you want to shrink or move an element within the view, use the bounds! 
Copy the code

15. Frame is a frame, and bounds is what displays child views.

  1. For bound points, it doesn’t change the origin of the frame, it changes the origin of the bounds itself, which affects the display position of the “child view”. This action is more like moving the origin of bounds.
  2. For bound’s size: it can change the frame. If the size of the bounds is larger than the size of the frame. So the frame is going to get bigger, so the origin of the frame is going to change. It’s more like a boundary.

14. Frame defines a frame (container) relative to the superview, and bounds is the real display area. If the bounds are smaller than the frame, they can be placed in the frame. If the bounds are larger than the frame, it feels like the frame is “stretched.” Frame becomes {{25, 25}, {250, 250}}. How did you get 25? The bounds are 50 pixels longer and 50 pixels wider than the frame, so the four edges balance out and overflow by “25” pixels each. As shown in the figure:

13. When using the block version of the container’s enumerator, an AutoreleasePool is automatically added internally:

[array enumerateObjectsUsingBlock: ^ (id obj, NSUInteger independence idx, BOOL * stop) {/ / here is surrounded by a local @ autoreleasepool}].Copy the code

Of course, it’s not available in regular for loops and for in loops, so the newer block version of the enumerator is more convenient. When iterating through a for loop produces a large number of AutoRelease variables, you need to manually add the local AutoreleasePool.

12. The best way to call a proxy object is to determine whether the object can respond to the method that will execute the proxy class. This way, the program will not crash due to an unrecognized selector error

11.convertPoint

[ViewA convertPoint:CGPointMake(0, Tp.y) toView:ViewB] // convertPoint:CGPointMake(0, // Convert the coordinates of a point in ViewB coordinate system to the coordinates of a point in ViewA coordinate system.Copy the code

9. Execution sequence of the two methods: HeightForRowAtIndexPath the proxy method is executed first, Set the height of the corresponding cell in cellForRowAtIndexPath, and then return the height of the corresponding cell in cellForRowAtIndexPath.

EstimateHeight is set and cellForRowAtIndexPath and then heightForRowAtIndexPath are executed

[blog.csdn.net/crayondeng/…].

8.// Keyboard occlusion processing

TextField -> textFild. superview->self.view - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ CGPoint sp=_svQues.contentOffset; CGPoint tp=textField.frame.origin; [textField. Superview convertPoint:CGPointMake(0, tP.y) toView:self.view]; // textField filed with self.view CGPoint temp=[textField. Superview convertPoint:CGPointMake(0, tP.y) toView:self.view]; sp.y+=temp.y; sp.y-=40; _svQues.contentOffset=sp; }Copy the code

Third-party library IQKeyBoardMannager