Adjust the leftBarButtonItem distance from the left of UINavigationBar.

UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-button-whiteArrow.png"] style:UIBarButtonItemStylePlain target:self action:@selector(logoutBarBtnPressed:)];

UIBarButtonItem *fixedBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

fixedBarButtonItem.width = -15;

self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:fixedBarButtonItem, buttonItem, nil];
Copy the code

fixedButton.width


RestKit saves data to Core Data

Save data to Core Data using RestKit, entity is

@interface Article : NSManagedObject

@property (nonatomic, retain) NSNumber* articleID;
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* body;
@property (nonatomic, retain) NSDate* publicationDate;

@end

@implementation Article // We use @dynamic for the properties in Core Data
@dynamic articleID;
@dynamic title;
@dynamic body;
@dynamic publicationDate;

@end
Copy the code

Set the object mapping

RKEntityMapping* articleMapping = [RKEntityMapping mappingForEntityForName:@"Article"
                                                      inManagedObjectStore:managedObjectStore];
[articleMapping addAttributeMappingsFromDictionary:@{
                                                     @"id": @"articleID"The @"title": @"title"The @"body": @"body"The @"publication_date": @"publicationDate"
                                                     }];

articleMapping.identificationAttributes = @[ @"articleID" ];
Copy the code

The array of values set by identity Attributes is used to determine whether the data returned is updated or new.


RestKit add relationship

Author Entity

@interface Author : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *email;

@end
Copy the code

Article Entity

@interface Article : NSObject

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *body;
@property (nonatomic) Author *author;
@property (nonatomic) NSDate *publicationDate;

@end
Copy the code

Add good friendship

// Create our new Author mapping
RKObjectMapping* authorMapping = [RKObjectMapping mappingForClass:[Author class] ];

// NOTE: When your source and destination key paths are symmetrical, you can use addAttributesFromArray: as a shortcut instead of addAttributesFromDictionary:

[authorMapping addAttributeMappingsFromArray:@[ @"name"The @"email" ]];

// Now configure the Article mapping
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class] ];
[articleMapping addAttributeMappingsFromDictionary:@{
                                                     @"title": @"title"The @"body": @"body"The @"publication_date": @"publicationDate"
                                                     }];

// Define the relationship mapping
[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"author"
                                                                               toKeyPath:@"author"
                                                                             withMapping:authorMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping
                                                                                        method:RKRequestMethodAny
                                                                                   pathPattern:nil keyPath:@"articles"
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Copy the code

The JTObjectMapping method is similar when going from Json to Model. Reduce a lot of work.


Xcode cannot find the device

Cause: The Deployment Target version is higher than the real version and cannot be found. Set the Deployment Target to match the system version of the real machine.


Autolayout automatic layout

AutoLayout needs to be in the – (void) shall become effective upon the execution of the viewDidLoad method, so I need the – (void) viewDidAppear: (BOOL) method to get the frame in animated, at this time to get to the correct frame.


Vi. Navigation backBarButtonItem setting

** According to Apple: BackbarbuttonItem doesn’t define customview, so, can only map or, make leftBarButtonItem custom back button, oneself write a method [self. NavigationController pop the current Item * *

Did you ever wonder why you set up code like this

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                               initWithTitle:@"Return"
                               style:UIBarButtonItemStylePlain
                               target:self
                               action:nil];

self.navigationItem.backBarButtonItem = backButton;
Copy the code

The word “back” does not appear on backButton.

I’m really confused by how leftBarButtonItem and rightBarButtonItem are set to the BarButtonItem on this page, BackBarButtonItem sets the BarButtonItem on the next page. For example: Two viewControllers, primary A and child B, we want to display “refresh” on the right BarButton on A and “retreat” on the BackButton on B, we should say in A’s viewDidLoad similar method:

UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"Refresh"
                                  style:UIBarButtonItemStylePlain
                                  target:self
                                  action:nil];

self.navigationItem.rightBarButtonItem = refreshButton;

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
                                 initWithTitle:@"Retreat"
                                 style:UIBarButtonItemStylePlain
                                 target:self
                                 action:nil];

self.navigationItem.backBarButtonItem = cancelButton;
Copy the code

B doesn’t have to do anything and then ApushB will do.


AFNetworking uses SSL

sharedClient.securityPolicy.allowInvalidCertificates = YES;
Copy the code

NSJSONSerialization data type requirements

When converting JSON, the following requirements must be met.

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

That is: nil, the underlying data cannot be converted to JSON.


NSArray for indefinite parameter processing

+ (NSArray *)arrayWithObjectsExceptionNil:(id)firstObj, ...
{
    NSMutableArray *tempMArray = [[NSMutableArray alloc] initWithCapacity:5];
    id eachObject = nil;
    va_list argumentList;
    
    if ( firstObj ) {
        [tempMArray addObject:firstObj];
        va_start(argumentList, firstObj);
        
        while ( (eachObject = va_arg(argumentList, id))){
            if( nil ! = eachObject ){ [tempMArray addObject:eachObject]; } } va_end(argumentList); }return nil;
}
Copy the code

Get the version

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; // App name NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"]; // App version NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; // app build version NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
Copy the code

** Note: AppID, which was generated in itunesConnect when the application was submitted, will not change after approval. **


No input file error

If the files are not found during compilation, delete the files that do not exist in Build Phases in Compile Sources, and add the missing files to the project.


12. CG, CF, CA, UI, etc

You can also see classes that start with other names like CF, CA, CG, UI, etc. So CFStringTokenizer which is a participle thing CALayer which is the layer of the Core Animation CGPoint which is a point UIImage which is the image inside the iPhone

CF refers to Core Foundation, CA refers to Core Animation, CG refers to Core Graphics, and UI refers to iPhone User Interface


13, File’s owner meaning

File’s owner is the class corresponding to xiB. For example, file’s owner of xiB file corresponding to view is the class corresponding to ViewController. File’s owner is the bridge between the view and the view Controller. (that is, how a view knows who should respond to its interface’s actions)


IOS Coin is not transparent

Generally, iOS app coins should be opaque, and you can’t use app coins more than once in the app.


15. Determine whether a custom class is repeated

In the custom library, two fixed methods of NSObject need to be overridden to determine if the class is duplicated:

- (BOOL)isEqual:(id)anObject;
- (NSUInteger)hash;
Copy the code

IOS macros

// Macro wrapper for NSLog only if debug mode has been enabled
#ifdef DEBUG
#define DLog(fmt,...) NSLog(fmt, ##__VA_ARGS__);
#else
// If debug mode hasn't been enabled, don't do anything when the macro is called
#define DLog(...)
#endif

#define MR_ENABLE_ACTIVE_RECORD_LOGGING 0

#define IS_OS_6_OR_LATER ([[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
#define IS_OS_7_OR_LATER ([[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define OBJISNULL(o) (o == nil || [o isKindOfClass:[NSNull class]] || ([o isKindOfClass:[NSString class]] && [o length] = = 0))
#define APP ((AppDelegate*)[[UIApplication sharedApplication] delegate])
#define UserDefaults [NSUserDefaults standardUserDefaults]
#define SharedApplication [UIApplication sharedApplication]
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] ! = NSOrderedDescending)
#define RGB(R, G, B) [UIColor colorWithRed: R /255.0 green: G /255.0 blue: B /255.0 alpha:1.0]
#define RGBA(r, G, B, a) [UIColor colorWithRed: R /255.0 green:g/255.0 blue: B /255.0 alpha:a]
Copy the code

17, judge whether it is 4 inch screen

#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
Copy the code

NSString format qualifier

specifier describe
% @ Objective – c objects
%zd NSInteger
%lx CFIndex
%tu NSUInteger
%i int
%u unsigned int
%hi short
%hu unsigned short
% % The % symbol

Declared variables are automatically initialized to nil under ARC

NSString *s;

In the non-ARC case, s points to any address, possibly the system address, causing a crash.

In the case of ARC, s has been automatically initialized to nil.


Add elements to NSArray, NSDictionary, etc

[_paths addObject:[_path copy]];

If this _path is nil, then there will be a crash. Because nil cannot be stored in a container, it can be stored with [NSNull null].

Pod ‘XTSafeCollection’, ‘~> 1.0.4’ third-party library is recommended to protect arrays from out of bounds, assignment nil, etc.


Ceil command floor command

An algorithm command in Math. Double ceil(double x); Power: Returns the smallest integer header file greater than or equal to the specified expression :math.h

floatF = 1.2222; NSLog(@"f is %f.", ceil(f));
Copy the code

Print: f is 2.000000.

Double floor(double x); double floor(double x); Header file: math.h

floatF = 1.2222; NSLog(@"f is %f.", floor(f));
Copy the code

Print: f is 1.000000.


Xcode makes a non-ARC setting for a class

In Xcode, click project, select “TARGETS” in your project, select “Compile Sources” in Build Phases, and find the class that you need to set to non-ARC. There is a “Compiler Flags” to the right of this class. Inside this set “-fno-objc-arc”. This class is compiled non-ARC.


23. Scrollview cannot be scrolled in a storyboard

The reason why scrollView scrolling can’t happen in storyboard is autolayout


24. Extend the startup time of the APP

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [NSThread SleepForTimeInterval: 3.0 f];return YES;

}
Copy the code

Xcode does not run watchdog during debugging

Watchdog does not run when debugging with Xcode. Do not connect the device to Xcode when the test program starts performance on the device.


Language internationalization NSLocalizedString

If you’re using Localizable. Strings, you can get strings like this in your program: NSLocalizedString(@”mykey”, nil) if you’re using strings with a custom name, like MyApp. Strings, then you can get strings in your program like this: NSLocalizedStringFromTable (@ “mykey” @ “MyApp”, nil) can obtain the string “myvalue” that can be any language.


27. Use of UIAppearance

Use UIAppearance to customize the appearance.

[+ appearance] Modifies the appearance of a class throughout the program

[[UINavigationBar appearance] setTintColor:myColor];
Copy the code

[+ appearanceWhenContainedIn:] when a class is contained within another class, to modify the appearance.

 [[UILabel appearanceWhenContainedIn:[cusSearchBar class], nil] setTextColor:[UIColor redColor]];
Copy the code

Convert NSString to UTF8 encoding NSString

In the use of network address, generally want to encode the URL into UTF8 format, otherwise in use may report the url does not exist error, then need to convert the following is the conversion function:

NSString *urlString= [NSString stringWithFormat:@"http://www.baidu.com"];
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL,  kCFStringEncodingUTF8 ));
NSURL *url = [NSURL URLWithString:encodedString];
Copy the code

Or use the following method:

NSString *utf8Str = @"Testing";
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
Copy the code

Sometimes the Chinese characters and other characters in the URL obtained are garbled, and the web content is garbled. Transcoding is needed to correctly identify NSString. The following method can be used:

// Solve the garble problem ()

NSString *transString = [NSString stringWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Copy the code

NSDateFormatter sets the date format AM

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mmaaa"];
NSDate *date = [NSDate date];
    
NSString *s = [dateFormatter stringFromDate:date];
Copy the code

The display effect is 10/05/2010 03:49pm


NSString is a pure number

- (BOOL)isPureInt:(NSString*)string{NSScanner* scan = [NSScanner scannerWithString:string]; int val;return[scan scanInt:&val] && [scan isAtEnd]; } - (BOOL)isPureFloat:(NSString*)string{NSScanner* scan = [NSScanner scannerWithString:string];float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

if(! [self isPureInt:insertValue.text] || ! [self isPureFloat:insertValue.text]) { resultLabel.textColor = [UIColor redColor]; resultLabel.text = @"Warning: Contains illegal characters, please enter pure numbers!";
    
    return;
}
Copy the code

31. Correct use of image

There are two ways to load a UIImage from an app bundle in iOS. The first is more common: imageNamed and the second is rarely used: Image with Content file Why are there two ways to do the same thing? The advantage of imageNamed is that it can cache images that are already loaded. Here’s what apple’s documentation says: This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object. This method looks for the image in the system cache by the name specified and returns it if it finds one. If the image is not found in the cache, the method loads the image data from the specified file, caches it, and returns the result. The imageWithContentsOfFile method simply loads the image and does not cache the image. The two methods can be used as follows:

UIImage *img = [UIImage imageNamed:@"myImage"]; // caching  
// or  
UIImage *img = [UIImage imageWithContentsOfFile:@"myImage"]; // no caching 
Copy the code

So how to choose? If you load a large image and use it only once, there is no need to cache the image. This case imageWithContentsOfFile is appropriate — the system doesn’t waste memory caching images.

However, if you often need to reuse images in your program, it is best to choose the imageNamed method. This method saves the time of loading images from disk every time.


32. Enlarge the middle part of the picture

According to the image up, down, left and right four pixels for automatic expansion.

UIImage *image = [UIImage imageNamed:@"png-0016"];
UIImage *newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(50, 50, 50, 50) resizingMode:UIImageResizingModeStretch];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 400)];
imageView.image = newImage;
imageView.contentMode = UIViewContentModeScaleAspectFill;
Copy the code

Method of use – (UIImage *) resizableImageWithCapInsets: UIEdgeInsets capInsets resizingMode: (resizingMode UIImageResizingMode) NS_AVAILABLE_IOS(6_0); The interior is resized according to the resizingMode, Can use UIImageResizingModeTile and UIImageResizingModeStretch two stretching mode. ** Note: ** This method returns a new UIImage that needs to be used.

Note: UIEdgeInsets should not cross up, down or left, or they will be blank.

The new feature Slicing in Xcode5 also allows you to set images directly without having to do it in code.


UIImage and NSData conversion

NSData *imageData = [NSData dataWithContentsOfFile:imagePath]; UIImage *aimage = [UIImage imageWithData:imageData]; NSData *imageData = UIImagePNGRepresentation(aimage);Copy the code

NSDictionary and NSData conversions

// NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
    
// NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
Copy the code

35, NSNumberFormatter price uses currency mode

If the value displayed is price, use money mode

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
self.introView.guaranteedDataLabel.text = [formatter stringFromNumber:self.quoteEntity.guranteedInfo.guaranteedPrice];
Copy the code

36. The method of drawing dotted lines

CGFloat lengths[] = {5, 5};

CGContextRef content = UIGraphicsGetCurrentContext();

CGContextBeginPath(content);

CGContextSetLineWidth(content, LINE_WIDTH);

CGContextSetStrokeColorWithColor(content, [UIColor blackColor].CGColor);

CGContextSetLineDash(content, 0, lengths, 2);

CGContextMoveToPoint(content, 0, rect.size.height - LINE_WIDTH);

CGContextAddLineToPoint(content, rect.size.width, rect.size.height - LINE_WIDTH);

CGContextStrokePath(content);

CGContextClosePath(content);
Copy the code

37. Screen rotation of equipment

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeLeft;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeLeft;
}
Copy the code

So if you set up your storyboard to only support portrait, you can add these three methods to a single UIViewController so that that UIViewController only supports left landscape.


UITextField pops up UIDatePicker

Set the inputView of UITextField to pop up UIDatePicker instead of the keyboard.

The first thing you need to do is specify the text InputView at the end of the View load

UIDatePicker *datePicker = [[UIDatePicker alloc] init];  
datePicker.datePickerMode = UIDatePickerModeDate;  
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];  
self.txtDate.inputView = datePicker;  
Copy the code

Then you need to specify what the event is when UIDatePicker changes. This is to assign a value to the text box.

- (IBAction)dateChanged:(id)sender  
{  
    UIDatePicker *picker = (UIDatePicker *)sender;  
    self.txtDate.text = [NSString stringWithFormat:@"% @", picker.date];
   
}  
Copy the code

Then when the text box is finished editing, you need to make the UIDatePicker disappear.

- (IBAction)doneEditing:(id)sender  
{  
    [self.txtDate resignFirstResponder];  
}  
Copy the code

Then place the textbox in IB and point to the defined txtDate


39. Set the Status Bar font to white

  1. In the Info. Set in the plist UIViewControllerBasedStatusBarAppearance to NO

  2. In the ViewController that needs to change the status bar color add to the ViewDidLoad method:

UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
Copy the code

If you need to change color in all views, you can do so in the parent class’s related methods.


Forty, UILongPressGestureRecognizer 2 times

/ / call 2 times, at the beginning and at the end of the - (void) hello: (longPress UILongPressGestureRecognizer *) {if(longPress. State = = UIGestureRecognizerStateEnded) / / need to add a judge {NSLog (@"long");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"hello"
                              
                                                        message:@"Long Press"
                              
                                                       delegate:self
                              
                                              cancelButtonTitle:@"OK"otherButtonTitles:nil, nil]; [alert show]; }}Copy the code

View events are responded to one at a time

self.scrollView.exclusiveTouch = YES;
Copy the code

Set the ‘exclusiveTouch’ attribute to YES.


Immediate response operation in UIScrollView

The delaysContentTouches property is an immediate response to the Touch event in the UIScrollView. The default is YES, and set this value to NO if you want an immediate response after clicking.


UITableView Add custom view to Cell

If you add a custom UIView to a UITableView, note that the color in the view will change irrevocably due to the color of the selected Cell.


NSNotificationCenter logout

When NSNotificationCenter registers a notification

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullableNSString *)aName object:(nullableid)anObject;
Copy the code

Be sure to use this in class’s dealloc

- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;
Copy the code

Log out.

– (void)removeObserver:(id)observer; Unregister a notification.

Note: If you do not log out, the class will not be released.


45. Disadvantages of H5 development

The downside of H5 development: Too much content. When H5 is opened, it will take up a lot of memory, as seen in the project, usually up to 50 MB of memory per page.


46, interactivepopgesturerecognizer use

After setting the left bar button, the effect returned by right swipe will be invalid.

In order to retrieve the event returned by the right swipe, run

[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(back)];
Copy the code

** added in ViewController viewDidAppare, removed in viewWillDisappear. **


I’ll post a layout between two UIViews

[self.bottomOpenStoreBtn mas_remakeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(promptImageView.mas_bottom).with.offset(30); make.height.mas_equalTo(44);  make.width.mas_equalTo(SCREEN_WIDTH - 30); make.centerX.mas_equalTo(self.promptScrollView);  make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30); }];Copy the code

Set the distance between the top of self.bottomOpenStoreBtn and the top of promptImageView to 30pt make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30); Of the self. PromptScrollView. Mas_bottom mas_bottom must be used, can’t use bottom.

Make the top of the top for – (MASConstraint *) top and self. PromptScrollView. The bottom is in the bottom

- (float) bottom
{    return CGRectGetMaxY (self.frame);
}
Copy the code

One is a layout property and the other is a frame property.