IOS (1)
7. Drag to stop, which is used to record relevant records when dragging to stop.
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0){
_svcontentOffsetY = _svQues.contentOffset.y;
}
Copy the code
6.strUrl1 = [strUrl1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You can get the navigationController in the navigationController’s Delegate
using the UINavigationControllerDelegate you can use thenavigationController:willShowViewController:animated: method to access the navigationBar
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}
Copy the code
4. MAC Four fingers push forward – Taskbar MAC five fingers spread out – Desktop five fingers close -lunch Two fingers – scroll
- view.userInteractionEnabled=NO; Let a view disable the response
2.totalBytesExpectedToRead in setDownloadProgressBlock remains -1 until download is done
Download progress may return -1 if the server does not set the Content-Length HTTP header in the response. In this case, it is recommended that you use an indeterminate progress indicator instead.
1.NSURLSession is a new class introduced in iOS 7 to replace NSURLConnection. NSURLConnection is not deprecated, and probably won’t be for some time, but NSURLSession is the future of networking in Foundation, and it’s a good one, because it improves on many of the shortcomings of the past
PopToViewController API usage 1.UIWebView zoom control
2.UIScrollView support for keyboard timing
[[UIScreen mainScreen] applicationFrame] [[UIScreen mainScreen] Bounds] CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame]; UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect]; CGRect fullScreenRect=[[UIScreen mainScreen] bounds]; UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];Copy the code
Corresponding display:
2. For the index of the subview, the index of the last subview added is 0
UIView UIView *redView = [[UIView Alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; redView.backgroundColor = [UIColor redColor]; [self.view addSubview:redView]; UIView UIView *yellowView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; yellowView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:yellowView]; / / / / child view index is 2 UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [button setTitle: @ "change" forState: UIControlStateNormal]; button.frame = CGRectMake(10, 10, 300, 40); [self.view addSubview:button]; / / child view index is 1 UIButton * for = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [for the setTitle: @ "change 1" forState: UIControlStateNormal]; button1.frame = CGRectMake(10, 60, 300, 40); [self.view addSubview:button1]; Self. view exchangeSubviewAtIndex:2 withSubviewAtIndex:3; self.view exchangeSubviewAtIndex: 3;Copy the code
3. Zoom in and out of pictures:
To implement the UIScrollViewDelegate protocol
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIImage *image = [UIImage imageNamed:@"big.jpg"]; self.iv = [[UIImageView alloc] initWithImage:image]; self.iv.frame = CGRectMake(0, 0, image.size.width, image.size.height) ; CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame]; UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect]; [scrollView addSubview:self.iv]; scrollView.contentSize=CGSizeMake(image.size.width ,image.size.height); scrollView.delegate=self; ScrollView. MinimumZoomScale = 0.2; ScrollView. MaximumZoomScale = 2.0; [self.view addSubview:scrollView]; } -(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{ CGPoint upperLeftOfVisible = scrollView.contentOffset; NSLog(@"x:%f, y:%f", upperLeftOfVisible.x, upperLeftOfVisible.y); } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.iv; }Copy the code
4. General code to achieve view animation effect:
Add multiple views as in Example 2, and then switch views by setting index
- (void)changeUIView{ [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration: 1.0 f]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES]; self.view exchangeSubviewAtIndex:2 withSubviewAtIndex:3]; [UIView commitAnimations]; // Add this sentence, you can have multiple views commitAnimations; }Copy the code
5. Differences between presentViewController and pushViewController
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addViewController]; [self.navigationController presentModalViewController:navController animated:YES]; [self.navigationController pushViewController:navController animated:YES]; //presentViewController: Indicates that the user needs to do something, enter a password, add data, etc., and the user must do or cancel before doing anything else It allows the user to browse the information, and the user can decide which page to go forward or return to:Copy the code
IOS UI: pop-up view/popup modal presentViewController presentModalViewController (IOS 6.0) — – blog channel – CSDN.NET IOS sunshinexyj column Users most often see two kinds of Animations that switch ViewControllers:
5. Check the bounds property of the view in the LLDB
P (CGRect)[view bounds] or p view.layer.boundsCopy the code
6. Use two views for screen rotation
Reference: View Controller Programming Guide for iOS: Supporting Multiple Interface Orientations
@implementation PortraitViewController - (void)awakeFromNib{// First add notification for the rotation of the screen isShowingLandscapeView = NO; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)orientationChanged:(NSNotification *)notification{// display different controllers according to different screen layouts UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation; if (UIDeviceOrientationIsLandscape(deviceOrientation) && ! isShowingLandscapeView) { [self performSegueWithIdentifier:@"DisplayAlternateView" sender:self]; isShowingLandscapeView = YES; } else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView) { [self dismissViewControllerAnimated:YES completion:nil]; isShowingLandscapeView = NO; }}Copy the code
7.UIView background Settings,UIView transparency Settings,UITextView rounded corners Settings
[super viewDidLoad]; UIGraphicsBeginImageContext(self.view.frame.size); [[UIImage imageNamed:@"viewback.jpeg"] drawInRect:self.view.frame]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.view.backgroundColor = [UIColor colorWithPatternImage:image]; UIView* v=[[UIView alloc] initWithFrame:self.view.frame]; [v setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]]; v.bounds=CGRectMake(-50, -50, self.view.frame.size.width, self.view.frame.size.height); CGRect r=CGRectMake(0, 0, self.view.frame.size.width-100, self.view.frame.size.height-200); UITextView* tv=[[UITextView alloc] initWithFrame:r]; tv.text=@"asdjflajsdlfkjalskfjalskjdflasjflajsdflk\nsdkfjsadlkfjadlsfjadlsfj\n"; TV. BackgroundColor = [[UIColor grayColor] colorWithAlphaComponent: 0.5]; tv.clipsToBounds=YES; TV. Layer. The cornerRadius = 10.0 f; [v addSubview:tv]; [self.view addSubview:v];Copy the code
8. Optimization of pictures in ios programs
9. Requirements of IOS for JSON
9. How to determine whether the click is the desired view?
In order to check whether certain view inside another view was touched you can use hitTest. - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; In your custom implementation of touchesBegan check every touch in touches set. The point for hitTest method can be obtained using - (CGPoint)locationInView:(UIView *)view; method, where the view is your superView (the one that contains other views). EDIT: Here's a fast custom implementation: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint locationPoint = [[touches anyObject] locationInView:self]; UIView* viewYouWishToObtain = [self hitTest:locationPoint withEvent:event]; }Copy the code
I hope this was helpful, Paul
10. Add the long press gesture in a UIView subclass of course
-(void)initGR{
UILongPressGestureRecognizer *longPressGR = [[ UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPressGR.minimumPressDuration = 0.7;
[self addGestureRecognizer:longPressGR];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
[super setSelected:selected animated:animated];
}
- (BOOL)canBecomeFirstResponder{
return YES;
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer{
// if([self isHighlighted])
// {
[[self delegate] performSelector:@selector(showMenu:) withObject:self];
// }
}
Copy the code
11. Get the class name string
NSStringFromClass([instance class]) should do the trick.
if all you want to do is test an object to see if it's a type of a certain Class
BOOL test = [self isKindOfClass:[SomeClass class]];
Copy the code
12. Customize UIView
+(id)autolayoutViewWithCustomization:(BOOL)customize addLabel:(BOOL)addLabel{
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
if (customize) {
view.layer.cornerRadius = 4;
view.layer.masksToBounds= YES;
view.backgroundColor = [UIColor whiteColor];
view.layer.borderWidth = 1;
view.layer.borderColor = [UIColor lightGrayColor].CGColor;
}
if (addLabel) {
// Create a label here
[self addSubview:label];
}
return view;
}
Copy the code
13. A classification is used when using custom constraints
@implementation UIView (Autolayout)
+(id)autolayoutView{
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
Copy the code
14. Horizontally centered, vertically centered addition
/ / this is necessary, the autoresizemask to the constraints of the automatic translation, in order to use custom constraints imagevew. TranslatesAutoresizingMaskIntoConstraints = NO; Read / / the Internet must be combined with the height and width of the picture constraints can, tried, without also line / / [imagevew addConstraint: [NSLayoutConstraint constraintWithItem: imagevew attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute Constant multiplier: 1.0:200.0]]; // [imagevew addConstraint:[NSLayoutConstraint constraintWithItem:imagevew attribute:NSLayoutAttributeHeight RelatedBy: NSLayoutRelationEqual toItem: nil attribute: NSLayoutAttributeNotAnAttribute multiplier: constant 1.0:150.0]]. // Calculate formula: Imagevew.attr = self.view.attr*multiplier+constant [self.view addConstraint:[NSLayoutConstraint constraintWithItem:imagevew attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view Attribute: NSLayoutAttributeBottom multiplier: 0.5 constant: 0]]; / / horizontal center [self view addConstraint: [NSLayoutConstraint constraintWithItem: imagevew attribute: NSLayoutAttributeCenterX RelatedBy: NSLayoutRelationEqual toItem: self. The view attribute: NSLayoutAttributeRight multiplier: 0.5 constant: 0]]; / / the following program can also be used to implement the center / / [self. View addConstraint: [NSLayoutConstraint constraintWithItem: imagevew attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]]; / / horizontal center / / [self view addConstraint: [NSLayoutConstraint constraintWithItem: imagevew attribute: NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];Copy the code
15.handle text changes for both text fields
[self.usernameTextField addTarget:self
action:@selector(usernameTextFieldChanged)
forControlEvents:UIControlEventEditingChanged];
[self.passwordTextField addTarget:self
action:@selector(passwordTextFieldChanged)
forControlEvents:UIControlEventEditingChanged];
Copy the code
16. The button text use setTitle: forState rather than self. OriginButton. TitleLabel. Text, otherwise will bring unexpected results
17.Stackoverflow.com/questions/2…
If the cells come from a storyboard or nib file, then initWithStyle:reuseIdentifier is not called, initWithCoder: is called instead. Here’s a typical implementation of an overwritten initWithCoder::
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
// Do your custom initialization here
}
return self;
}
Copy the code
18.www.timoliver.com.au/2012/01/14/…
@implementation UIScrollView (ZoomToPoint) - (void)zoomToPoint:(CGPoint)zoomPoint withScale: (CGFloat)scale animated: (BOOL) Animated {//Normalize current content size back to content scale of 1.0f CGSize contentSize; contentSize.width = (self.contentSize.width / self.zoomScale); contentSize.height = (self.contentSize.height / self.zoomScale); //translate the zoom point to relative to the content rect zoomPoint.x = (zoomPoint.x / self.bounds.size.width) * contentSize.width; zoomPoint.y = (zoomPoint.y / self.bounds.size.height) * contentSize.height; //derive the size of the region to zoom to CGSize zoomSize; zoomSize.width = self.bounds.size.width / scale; zoomSize.height = self.bounds.size.height / scale; //offset the zoom rect so the actual zoom point is in the middle of the rectangle CGRect zoomRect; X = zoomPoint.x -zoomsize.width / 2.0f; Y = zoomPoint. Y -zoomsize. Height / 2.0f; zoomRect.size.width = zoomSize.width; zoomRect.size.height = zoomSize.height; //apply the resize [self zoomToRect: zoomRect animated: animated]; } @endCopy the code
19.Stackoverflow.com/questions/2…
20. Call order of UIScrollView methods:
init-> initWithFrame->setFrame->layoutSubviews
21.UILabel adaptive height and line wrapping
UILabel *label = [[UILabel alloc] init]; NSString *text = @" This is a test!! Adsfsaf take place don't forget me don't forget me don't forget me don't forget me don't forget me don't forget me don't forget me don't forget me ; label.text = text; [label setNumberOfLines:0]; UIFont *font = [UIFont fontWithName:@"Arial" size:14]; // Set the font label.font = font; CGSize constraint = CGSizeMake(300, 20000.0f); CGSize size = [text sizeWithFont:font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; [label setFrame:CGRectMake(10, 0, size.width, size.height)]; [self.view addSubview:label];Copy the code
UIBarButtonItem * clearBtnItem = [[UIBarButtonItem alloc] initWithTitle: @ "cancel" style: UIBarButtonItemStylePlain target: nil action:nil]; UIBarButtonItem*flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem * selectAllBtnItem = [[UIBarButtonItem alloc] initWithTitle: @ "future generations" style: UIBarButtonItemStylePlain target:nil action:nil]; NSArray *toolbarItemsForManagingTheSelection = @[clearBtnItem, flexibleSpace,selectAllBtnItem]; [self setToolbarItems:toolbarItemsForManagingTheSelection animated:YES];Copy the code
23. The toolbar is displayed at the bottom
// UIBarButtonItem *uploadBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// [self setToolbarItems:[NSArray arrayWithObjects: uploadBtn,flexItem,nil]];
// [self.navigationController setToolbarHidden:NO animated:YES];
Copy the code
24. The IOS version
If ([[UIDevice currentDevice]systemVersion]floatValue]>=7.0) // {// self.edgesForExtendedLayout = UIRectEdgeNone; // self.automaticallyAdjustsScrollViewInsets = NO; / /}Copy the code
Why can’t I use retainCount
You should never use -retainCount, because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on. For example: * You'd think that `[NSNumber numberWithInt:1]` would have a retainCount of 1. It doesn't. It's 2. * You'd think that @"Foo" would have a retainCount of 1. It doesn't. It's 1152921504606846975. * You'd think that [NSString stringWithString:@"Foo"] would have a retainCount of 1. It doesn't. Again, it's 1152921504606846975. Basically, since anything can retain an object (and therefore alter its retainCount), and since you don't have the source to most of the code that runs an application, an object's retainCount is meaningless. If you're trying to track down why an object isn't getting deallocated, use the Leaks tool in Instruments. If you're trying to track down why an object was deallocated too soon, use the Zombies tool in Instruments. But don't use -retainCount. It's a truly worthless method. edit Please everyone go to http://bugreport.apple.com and request that -retainCount be deprecated. The more people that ask for it, the better. edit #2 As an update,[NSNumber numberWithInt:1] now has a retainCount of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.Copy the code
Ref: stackoverflow.com/questions/4…
About the resolution of ios mobile devices
IphoneX 0.5625 iphoneX 0.6666
UIColor transition
Here is a category for UIColor that can be used to linearly interpolate between two UIColors in either RGB or HSV:
@implementation UIColor (Interpolate)
+ (UIColor *)interpolateRGBColorFrom:(UIColor *)start to:(UIColor *)end withFraction:(float)f {
f = MAX(0, f);
f = MIN(1, f);
const CGFloat *c1 = CGColorGetComponents(start.CGColor);
const CGFloat *c2 = CGColorGetComponents(end.CGColor);
CGFloat r = c1[0] + (c2[0] - c1[0]) * f;
CGFloat g = c1[1] + (c2[1] - c1[1]) * f;
CGFloat b = c1[2] + (c2[2] - c1[2]) * f;
CGFloat a = c1[3] + (c2[3] - c1[3]) * f;
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
+ (UIColor *)interpolateHSVColorFrom:(UIColor *)start to:(UIColor *)end withFraction:(float)f {
f = MAX(0, f);
f = MIN(1, f);
CGFloat h1,s1,v1,a1;
[start getHue:&h1 saturation:&s1 brightness:&v1 alpha:&a1];
CGFloat h2,s2,v2,a2;
[end getHue:&h2 saturation:&s2 brightness:&v2 alpha:&a2];
CGFloat h = h1 + (h2 - h1) * f;
CGFloat s = s1 + (s2 - s1) * f;
CGFloat v = v1 + (v2 - v1) * f;
CGFloat a = a1 + (a2 - a1) * f;
return [UIColor colorWithHue:h saturation:s brightness:v alpha:a];
}
@end
Copy the code
Ref:stackoverflow.com/questions/2…
Use constraints when there are pictures
When you have an image and do not explicitly specify the size of the image and want to rely on the constraint to determine the size, be aware that the image is being pulled out of shape.
If you have an existing color, you can return a new one with a specified alpha, like this:
Color - (void) setBackgroundColor (UIColor *) {self. The backgroundColor = [color colorWithAlphaComponent: 0.3 f]; }Copy the code
Get to UIViewController from UIView on iPhone
Using the example posted by Brock, I modified it so that its a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.
@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end
@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
// convenience function for casting and to "mask" the recursive function
return (UIViewController *)[self traverseResponderChainForUIViewController];
}
- (id) traverseResponderChainForUIViewController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return nextResponder;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUIViewController];
} else {
return nil;
}
}
@end
Copy the code
To use this code, add it into an new class file (I named mine “UIKitCategories”) and remove the class data… copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import “UIKitCategories. H” and use within the UIView code:
// from a UIView subclass… returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];
Ref:stackoverflow.com/questions/1…
Drag move button
- (void)viewDidLoad { [super viewDidLoad]; UIButton * btn=[[UIButton alloc]initWithFrame:CGRectMake(20, 40, 50, 50)]; [self.view addSubview:btn]; btn.backgroundColor=[UIColor redColor]; [btn addTarget:self action:@selector(dragBegan:withEvent: ) forControlEvents: UIControlEventTouchDown]; [btn addTarget:self action:@selector(dragMoving:withEvent: ) forControlEvents: UIControlEventTouchDragInside]; [btn addTarget:self action:@selector(dragEnded:withEvent: ) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; } - (void) dragBegan: (UIControl *) c withEvent:ev{ NSLog(@"dragBegan......" ); } - (void) dragMoving: (UIControl *) c withEvent:ev{ NSLog(@"dragMoving.............." ); UIButton *bt = (UIButton *)c; c.center = [[[ev allTouches] anyObject] locationInView:self.view]; } - (void) dragEnded: (UIControl *) c withEvent:ev{ NSLog(@"dragEnded.............." ); UIButton *bt = (UIButton *)c; c.center = [[[ev allTouches] anyObject] locationInView:self.view]; }Copy the code
Stackoverflow.com/questions/4…
The actual use of the Opaque property
-
From this, the opaque property’s real purpose is to provide a performance tuning switch for the drawing system!
According to the logic above, when opaque property is set to YES, the GPU will not use the layer color composition formula to synthesize the real color value. Therefore, if opaque is set to YES and the corresponding UIView’s alpha property is not 1.0, something unexpected will happen
The relationship and difference between the alpha, hidden and opaque properties of UIView – CSDN.NET
- Just check the opaque property of the red view and set it to YES. Blended layer will not work if the backgroundColor is clear color, blended layer will not work if the backgroundColor is clear color. Think for yourself
(The default background color is 1 and transparent, so you need to set a background color. If alpha<1, opaque cannot be set to yes, otherwise color confusion will occur.)
Hide the table’s extra dividers
UIView *view =[ [UIView alloc]init];
view.backgroundColor = [UIColor clearColor];
[tableView setTableFooterView:view];
Copy the code
When a page has both a UIScrollView and a UITableView, and both agents are set to self. UITableview will also call the following proxy.
/ / view release - (void) scrolling scrollViewDidEndDecelerating: (scrollView UIScrollView *) {if ([scrollView isEqual: self. ConScrollView]) { / / adjust the top slider button state int tag = (int) scrollView. ContentOffset. X/self. The bounds. Size. Width + 100; UIButton* button=(UIButton*)[self.view viewWithTag:tag]; [button sendActionsForControlEvents:UIControlEventTouchUpInside]; }}Copy the code
[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];
about iphone keychain
iphone keychain items persist after application uninstall?
Yes, this is the expected and correct behavior. Some keychain items may be shared with other apps you control (that share the same keychain item access group). You should just leave the info alone when your app is removed. You have no callback The or method of o the keychain items on deletion of your app. The ref: stackoverflow.com/questions/3… keychain and provisiong profile
Note: On iPhone, Keychain rights depend on the provisioning profile used to sign your application. Be sure to consistently use the same provisioning profile across different versions of your application. Check for more information Keychain Services Programming Guide.
Developer.apple.com/library/ios… Stackoverflow.com/questions/1…
When the height of a view is zero, its subviews are still displayed, if not displayed
Can be set as follows: the self. TipConview. ClipsToBounds = YES;
When removing cells from a UITableView, note the following:
- 1. Delete the data first, and then deleteRowsAtIndexPaths: WithRowAnimation
- 2. If there are no rows in the corresponding setion, delete the setion and numberOfSetions.
- 3. Place the delete operation between beginUpdates and endUpdates
- 4. ReloadData if you want to synchronize the table’s cell and datasource
-(void)deleteLocalRowWithIndexPath:(NSIndexPath*)indexPath{
NSString* keyStr=[self.doingHeaderArray objectAtIndex:indexPath.section];
NSMutableArray* arr=[self.doingDic objectForKey:keyStr];
[self.doingTable beginUpdates];
[arr removeObjectAtIndex:indexPath.row];
[self.doingTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationRight];
if(arr.count==0){
[self.doingHeaderArray removeObjectAtIndex:indexPath.section];
[self.doingTable deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
}
[self.doingTable endUpdates];
[self.doingTable reloadData];
}
Copy the code
Sets the selection style of the UITableView.
/ / when calling: [self doingTable selectRowAtIndexPath: indexPath animated: YES scrollPosition: UITableViewScrollPositionNone]; - (void)setSelected:(BOOL)selected animated:(BOOL)animated {[super setSelected:selected animated:animated]; if (selected) { self.contentView.backgroundColor=UIColorFromRGB(0xfafafa); } else { self.contentView.backgroundColor=[UIColor whiteColor]; }}Copy the code
Note when animating two subviews within a view
If two child view simply hidden switch, so remember to add UIViewAnimationOptionShowHideTransitionViews
[UIView transitionWithView: _doingTable superview duration: 0.7 options:UIViewAnimationOptionTransitionCurlDown|UIViewAnimationOptionShowHideTransitionViews animations:^(void){ _doingTable.hidden=NO; _historyTable.hidden=YES; } completion:^(BOOL finished){ }]; });Copy the code
}
[UIView transitionWithView: _doingTable superview duration: 0.7 options:UIViewAnimationOptionTransitionCurlUp|UIViewAnimationOptionShowHideTransitionViews animations:^(void){ _doingTable.hidden=YES; _historyTable.hidden=NO; } completion:^(BOOL finished){ }];Copy the code
ConvertRect :fromView:
-(void) keyboardWillShow:(NSNotification *)note{ if(self.currentTxt! =nil&&! self.keyboardIsShow){ CGRect keyboardBounds; [[note.userInfo valueFor Key:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds]; / / the right to convert the rect in tableviewcell, into the top view of the rect CGRect r1 = [_containerView convertRect: self. CurrentTxt. The bounds fromView:self.currentTxt]; [UIView animateWithDuration: 0.5 animations: ^ {_leaseScrollview. ContentOffset = CGPointMake (0, r1.origin.y+r1.size.height+keyboardBounds.size.height-_containerView.frame.size.height+5); }]; } self.keyboardIsShow=YES; }Copy the code
The copy function of the UITextView is disabled
Finally solved it by subclassing UITextView (created custom class for it) and just added
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(copy:)){
return NO;
}
return NO;
}
Copy the code
Inside of. M file of my custom TextView subclass. After that “Copy” doesn’t appear any more with or without [menu] update];
When you need to update a single TableView cell
- [UITableView reloadRowsAtIndexPaths: withAnimation:] / / can also use [demoTableView beginUpdates]; [demoTableView endUpdates]; // to force a table refresh.Copy the code
animate a height change on a UITableViewCell when selected?
A workaround when some method must be implemented in a subclass
You want to share some code between two similar classes. It’s easy to think of extracting a parent class, but some methods must be subclassed. There’s no such thing as an abstract class in Objective-C, you can only throw exceptions in the methods of the parent class, and the subclass doesn’t have any indication of which methods haven’t been implemented, which is pretty ugly. I wanted to extract Protolcol using big Java’s strategy pattern and hand the implementation over to different objects, but it was even more annoying that Blah blah blah introduced a bunch of files. All I can think of now is call back Block. Objc is capable of implementing Ruby-like mixins by dynamically adding methods at runtime, but I find it too hack. For example, in the parent class implementation, insert the following code to throw an exception directly:
[NSException raise:NSInternalInconsistencyException
format:@"WARNING: YOU MUST OVERRIDE THIS GETTER IN YOUR CUSTOM VIEW .M FILE"];
Copy the code
To change the status bar
Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file. In the viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate]; Add the following method:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
Copy the code
Note: This does not work for controllers inside UINavigationController, please see Tyson’s comment below 🙂
Stackoverflow.com/questions/1…
Some usage of UITableView.
[tableView scrollToRowAtIndexPath:[tView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES]; [tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade]; [tableView reloadRowsAtIndexPaths:modifiedRows withRowAnimation:UITableViewRowAnimationAutomatic]; Directly using the view: xib LeaseEquMainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: @ "doingcell"]. //TODO if(cell==nil){ NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"LeaseEquMainTableViewCell" owner:nil options:nil]; cell = (LeaseEquMainTableViewCell *)[nibs objectAtIndex:0]; }Copy the code
Enable UITableView deletion
// During startup (-viewDidLoad or in storyboard) do:
self.tableView.allowsMultipleSelectionDuringEditing = NO;
// Override to support conditional editing of the table view.
// This only needs to be implemented if you are going to be returning NO
// for some items. By default, all items are editable.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
Copy the code
Stackoverflow.com/posts/33097…
Automatically adjust font size in lable to the appropriate size
I think you just need to add this:
label.adjustsFontSizeToFitWidth = YES;
label.minimumFontSize = 0;
Copy the code
Then the text will automatically resize to fit the label.
Note however that this will only really work if the label.numberOfLines = 1, so that the text is on a single line. If you need the text to wrap onto multiple lines but still shrink to fit, the solution is more complex. To do this, you need to calculate the rendered size of the text and then reduce it in a loop, as follows:
NSString *theText = @"A long string"; CGRect labelRect = CGRectMake(10, 50, 300, 50); label.adjustsFontSizeToFitWidth = NO; label.numberOfLines = 0; CGFloat fontSize = 30; While (fontSize > 0.0){CGSize size = [theText sizeWithFont:[UIFont fontWithName:@"Verdana" size:fontSize] constrainedToSize:CGSizeMake(labelRect.size.width, 10000) lineBreakMode:UILineBreakModeWordWrap]; if (size.height <= labelRect.size.height) break; FontSize = 1.0; } //set font size label.font = [UIFont fontWithName:@"Verdana" size:fontSize];Copy the code
We’ll create the placeholder for our TextView
uilabel keypath Easy way, just create placeholder text in UITextView by using the following UITextViewDelegate methods:
- (void)textViewDidBeginEditing:(UITextView *)textView{ if ([textView.text isEqualToString:@"placeholder text here..."] ) { textView.text = @""; textView.textColor = [UIColor blackColor]; //optional } [textView becomeFirstResponder]; } - (void)textViewDidEndEditing:(UITextView *)textView { if ([textView.text isEqualToString:@""]) { textView.text = @"placeholder text here..." ; textView.textColor = [UIColor lightGrayColor]; //optional } [textView resignFirstResponder]; }Copy the code
just remember to set myUITextView with the exact text on creation e.g.
UITextView *myUITextView = [[UITextView alloc] init]; myUITextView.delegate = self; myUITextView.text = @"placeholder text here..." ; myUITextView.textColor = [UIColor lightGrayColor]; //optionalCopy the code
and make the parent class a UITextViewDelegate before including these methods e.g.
@interface MyClass () <UITextViewDelegate>
@end
Copy the code
Stackoverflow.com/questions/1…
Inversion array
There is a much easier solution, if you take advantage of the built-in reverseObjectEnumeratormethod on NSArray, and the allObjects method of NSEnumerator:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
Copy the code
Because allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, it strongly implies that those objects will be delivered in order of the enumerator. It even points out that after calling allObjects, the next object on the enumerator will be nil
_statusArray = @ [@ "applications," @ "apply for approval," @ "application verification through," @ "granted," @ "don't agree with," @ "in delivery", @ "lease", @" Renewal Application ",@" Renewal in progress ",@" Failed in renewal examination ",@" Recovery application ",@" confirmed recovery "]; NSInteger statusInt=detailInfo.zlzt.integerValue; NSArray* tempStatusArr=[self.statusArray subarrayWithRange:NSMakeRange(0, statusInt)] ; NSPredicate* pred=[NSPredicate predicateWithFormat:@"NOT CONTAINS 'NOT '"]; NSArray* tempArr=[tempStatusArr filteredArrayUsingPredicate:pred]; NSArray* reversedArray = [[tempArr reverseObjectEnumerator] allObjects];Copy the code
UIButton needs to set its own selected state
Just set selected when you call the method on button click event… for example..
-(IBAction) btnCheckBoxMale_Clicked:(id)sender{
[btnCheckBoxMale setSelected:YES];
}
Copy the code
Error: Cell animation stop fraction must be greater than start fraction
I experienced the same crash when trying to use a dummy footer to remove potential “empty” table view cells solution was to get rid of
tableView:viewForFooterInSection:
tableView:heightForFooterInSection:
Copy the code
and replace them with the following, in viewDidLoad :
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
Copy the code
Yes i also face this type of problem,do one thing just remove footer view.
Stackoverflow.com/questions/1…
Tell UIScrollView to scroll to the top
UPDATE FOR iOS 7
[self.scrollView setContentOffset:
CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
Copy the code
ORIGINAL
[self.scrollView setContentOffset:CGPointZero animated:YES];
Copy the code
or if you want to preserve the horizontal scroll position and just reset the vertical position:
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0) animated:YES];
Copy the code
Stackoverflow.com/questions/9…
Be careful when declaring Pointers in OC
You should declare your constant string as follows:
NSString * const kSomeConstantString = @""; // constant pointer
Copy the code
instead of:
const NSString * kSomeConstantString = @""; // pointer to constant
// equivalent to
NSString const * kSomeConstantString = @"";
Copy the code
The former is a constant pointer to an NSString object, while the later is a pointer to a constant NSString object.
Using a NSString * const prevents you from reassigning kSomeConstantString to point to a different NSString object. The method isEqualToString: expects an argument of type NSString . If you pass a pointer to a constant string (const NSString ), you are passing something different than it expects. Besides, NSString objects are already immutable, So making them const nsstrings is meaningless. Stackoverflow.com/questions/6…
To add space between the cells of a UITableView, either set the footer or leave extra space on the cell
- (CGFloat) tableView: (UITableView *) tableView heightForFooterInSection: (NSInteger) section {return 5.0; }Copy the code
Sets the highlighting of the UITableView Cell selection
You can do this as follows. Set your table cell ‘s selection style to UITableViewCellSelectionStyleNone. This will remove the blue background highlighting. Then, to make the text label highlighting work the way you want, instead of using the default UITableViewCell class, create a subclass of UITableViewCell and override the default implementation of setHighlighted:animated with your own implementation that sets the label colors to however you want depending on the highlighted state.
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{ if (highlighted) { self.textLabel.textColor = [UIColor whiteColor]; } else { self.textLabel.textColor = [UIColor blackColor]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sMenuStoreCell forIndexPath:indexPath]; // configure your cell here // this is where you set your color view UIView *customColorView = [[UIView alloc] init]; CustomColorView. BackgroundColor = [UIColor colorWithRed: 180/255.0 green: 138/255.0 blue: 171/255.0 alpha: 0.5]; cell.selectedBackgroundView = customColorView; return cell; }Copy the code
Set the long press gesture
if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
[self.doingTable selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionNone];
Copy the code
48.Should IBOutlets be strong or weak under ARC?
Summarized from the developer library: From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because: Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership. The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;
Copy the code
Patterns for Managing Outlets Become Consistent Across Platforms
The patterns for declaring outlets in iOS and OS X change with ARC and become consistent across both platforms. The pattern you should typically adopt is: outlets should be weak, Except for those from File’s Owner to top-level objects in a NIb File (or a storyboard scene) which should be strong. Full details are given in Nib Files in Resource Programming Guide. The ref: stackoverflow.com/questions/7… Stackoverflow.com/questions/2… Developer.apple.com/library/ios…
47.Whats the difference between sizeToFit, sizeThatFits, and sizeWithAttributes?
When sizing a UILabel to fit, what’s the difference between the 3 following methods of doing it:
1 -CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
CGSize adjustedSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
2 - [label sizeToFit]
3 - [label sizeThatFits..]
Copy the code
SizeToFit can make UILabel relayout its bounds based on it's contents. SizeThatFit can calculate the size of UILabel's Contents. SizeWithAttributes can calculate a string's size with attributes you passed.Copy the code
[self.tableview registerclass:[uitableviewcell class] forcellreuseidentifier:viewcontrollercellreuseidentifier]; uiview *view = [[uiview alloc] initwithframe:cgrectmake(100, 100, 200, 100)]; view.backgroundcolor = [uicolor yellowcolor]; uilabel *label = [[uilabel alloc] initwithframe:cgrectmake(5, 5, 0, 0)]; [label setfont:[uifont systemfontofsize:20]]; label.text = @"hello wdszgrf"; cgsize sizethatfits = [label sizethatfits:cgsizezero]; nslog(@"---- %f %f ----", sizethatfits.width, sizethatfits.height); / / the output: - 117.000000-24.000000 nslog (@ "f * * * * % % f * * * *", label, frame, the size, width, label. Frame. The size, height); // output: **** 0.000000 0.000000 **** sizethatSize does not change the original label size [label sizetofit]; [label setCenter: cgPointMake (80, 50)] [label setCenter: cgPointMake (80, 50)]] nslog(@"==== %f %f ====", label.frame.size.width, label.frame.size.height); // output: ==== 117.000000 24.000000 ==== [view addsubView :label]; [self.view addsubview:view];Copy the code
46. UICollectionView: must be initialized with a non-nil layout parameter
The crash is telling you pretty explicitly what is going wrong:
UICollectionView must be initialized with a non-nil layout parameter.
If you check the Apple documentation for UICollectionView, you’ll find that the only initializer is initWithFrame:collectionViewLayout:. Further, in the parameters for that initializer, you’ll see:
frame The frame rectangle for the collection view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This frame is passed to the superclass during initialization. layout The layout object to use for organizing items. The collection view stores a strong reference to the specified object. Must not be nil. Copy the code
I’ve bolded the important part. You must use initWithFrame:collectionViewLayout: to initialize your UICollectionView, and pass it a non-nil UICollectionViewLayout object. One way to fix this, then, would be to simply change the order of initialization you do:
UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.itemSize = CGSizeMake(100, 100);
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
[self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"cell"];
Copy the code
45. Present the process:
1) presenting View finds its root view (except window). 2) 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. Conclusion: 1) The parent of the presenting view is Window and overwrites the whole window. 2) The original view stack will be removed after present, except window. presentViewControllerCopy the code
Analysis of complex time string
NSString* string = @"Wed, 3 Apr 2013 04:11:02 GMT";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate* inputDate = [inputFormatter dateFromString:string];
NSLog(@"date = %@", inputDate);
Copy the code
// You might see Locale, what does that do? According to the online information is to adapt to the Chinese environment, otherwise it will not recognize such as Wed, if the English environment is not needed. I guess that’s what it means. You can try to comment out both Locale statements and see that it doesn’t work.
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:@"HH:mm:ss"];
NSString *str = [outputFormatter stringFromDate:inputDate];
NSLog(@"testDate:%@", str);
Copy the code
Yy: the last two digits of the year 3. Yyyy: the full year 4. MM: the month, displayed as 1-12 5. Dd: day, 2 digits, such as 02 8. D: Day, 1-2 digits, such as 2 9. EEE: abbreviated day of the week, such as Sun 10. M: minute, 1-2 bit 15. mm: minute, 2 bit 16. s: second, 1-2 bit 17. ss: second, 2 bit 18. s: second, 2 bit 18. s: second Ms 19.z: GMTCopy the code
Common time formats are:
1. yyyy-MM-dd HH:mm:ss.SSS
2. yyyy-MM-dd HH:mm:ss
3. yyyy-MM-dd
4. MM dd yyyy
Copy the code
43. The question is:
Normally, the IOS operating system will only ask you if you want to enable remote notification when you first install it on a new machine. So if the user chooses not to accept the push, the user can only go to the IOS system Settings to enable it again. For this situation, currently APP has no corresponding measures to deal with it.
Solution:
1. In the above case, if the user opens push in app Settings, the user will be prompted to open push of the corresponding app in IOS system Settings. When the user enables push in the user IOS system Settings, the APP will immediately get deviceToken, and then the deviceToken will be transmitted to the server in real time.Copy the code
For related entries, see :23
42. Get a screenshot of the View
Problem: You want to take a snapshot of a UIView as a UIImage.
Solution: It’s sometimes useful to create a UIImageView representing a visual snapshot of another UIView object. This new UIImageView can be useful for animation.
UIView *subView = self.viewWithManySubViews; UIGraphicsBeginImageContextWithOptions (subView. Bounds. The size, YES, 0.0 f); CGContextRef context = UIGraphicsGetCurrentContext(); [subView.layer renderInContext:context]; UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageView *snapshotImageView = [[UIImageView alloc] initWithImage:snapshotImage];Copy the code
Out of the screen, use window, their own baidu
Drag gesture animation
The kind of effects that you are describing as simulating a king of gravity/inertia can be produced by means of ease-out (start fast, end slow) and ease-in (start slow, end fast) timing functions. Support for easing out and easing in is available in iOS, so I don’t think you need any external library nor hard work (although, as you can imagine, your effect will need a lot of fine tuning). This will animate the translation of an object to a given position with an ease-out effect:
[UIView animateWithDuration: 2.0 delay: 0 options: UIViewAnimationOptionCurveEaseOut animations: ^ {self. The image. The center = finalPosition; }completion:NULL];Copy the code
If you handle your gesture through a UIPanGestureRecognizer, the gesture recognizer will provide you with two important information to calculate the final position: velocity and translation, which represent respectively how fast and how much the object was moved. You can install a pan gesture recognizer in your view (this would be the object you would like to animate, I guess) like this:
UIPanGestureRecognizer* panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
[yourView addGestureRecognizer:panGestureRecognizer];
[panGestureRecognizer release];
Copy the code
And then handle the animation in your handler:
-(void)handlePanFrom:(UIPanGestureRecognizer*)recognizer { CGPoint translation = [recognizer translationInView:recognizer.view]; CGPoint velocity = [recognizer velocityInView:recognizer.view]; if (recognizer.state == UIGestureRecognizerStateBegan) { } else if (recognizer.state == UIGestureRecognizerStateChanged) { <track the movement> } else if (recognizer.state == UIGestureRecognizerStateEnded) { <animate to final position> } }Copy the code
shareimprove this answer
40.Format string, integer with leading zeros
Use the format string “img_%03d.jpg” to get decimal numbers with three digits and leading zeros.
39. The ‘NSUnknownKeyException’… SetValue: forUndefinedKey:] :… not key value coding compliant
An error occurs at run time, mainly because attributes wired in IB disappear or have names changed in the corresponding code.
Stackoverflow.com/questions/1…
37. Apple’s view layout has changed a bit. Now the view defaults to full screen mode, while all bars (navigation bar, Tool bar, Search bars and Scope bars are translucent) and the Status bar is fully transparent.
In iOS7, UINavigationBar has a translucent property. By this, the view of the child VC of UINavigationViewController is under UINavigationBar by default. If you don’t need to get an translucent effect, turn off this property using the following code.
self.navigationController.navigationBar.translucent = NO
36. The QuickLook function
Apple introduced a nice feature called Quick Look in Leopard. With just a hit on the spacebar (or the combination of Command + Y), users could ‘peek’ into the selected file in the Finder (or some other application).
35.Xcode 6 iOS emulator app directory changes.
| | | | | | | | | | | | | | | | | | | | | | | | | | | |
Xcode directory is changed to 6 ~ / Library/Developer/CoreSimulator/Devices / {Device_ID} / data/Containers/Bundle/Application / / {Application_ID}
The Device_ID and Application_ID are a string of UUID. If you want to find the Device_ID corresponding to different emulators, you can run the xcrun simctl list command in Terminal
34. Why do WE need a copy here
@interface SomeClass : NSObject
@property (nonatomic, retain) NSString* text;
@end
...
SomeClass* test = [[SomeClass alloc] init];
NSMutableString* string = [[NSMutableString alloc] initWithString:@"cat"];
Copy the code
// Set [test setText:string] is the base class of NSMutableString. [string appendString:@"dog"]; // Changing string at this point affects the value of the text property in the test instance above, which is not the expected behavior.Copy the code
So change it to:
@property (nonatomic, copy) NSString* text;
Copy the code
ref:
- Copy vs. Retain, Immutable vs Mutable | b2cloud
- Extension to read copy with mutableCopy,
- To regain the iOS – copy
33. Composition of attributes.
@interface Counter : NSObject
@property (nonatomic, retain) NSNumber *count;
@end;
Copy the code
The property declares two accessor methods. Typically, you should ask the compiler to synthesize the methods; however, it’s instructive to see how they might be implemented.
In the “get” accessor, you just return the synthesized instance variable, so there is no need for retain or release:
- (NSNumber *)count {
return _count;
}
Copy the code
In the “set” method, if everyone else is playing by the same rules you have to assume the new count may be disposed of at any time so you Have to take ownership of the object — by sending it a retain message — to ensure it won’t be. You must also relinquish ownership of the old count object here by sending it a release message. (Sending a message to nil is allowed in Objective-C, So the implementation will still work if _count hasn’t yet been set.) You must send this after [newCount retain] in case The two are the same object — you don’t want to cause it to be deallocated.
- (void)setCount:(NSNumber *)newCount {
[newCount retain];
[_count release];
// Make the new assignment.
_count = newCount;
}
Copy the code
Don’t Use Accessor Methods in Initializer Methods and dealloc The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:
- init {
self = [super init];
if (self) {
_count = [[NSNumber alloc] initWithInteger:0];
}
return self;
}
Copy the code
Blog.sina.com.cn/s/blog_55a8…
32. When does deviceToken change?
By requesting the device token and passing it to the provider every time your application launches, you help to ensure that the provider has the current token for the device. If a user restores a backup to a device other than the one that the backup was created for (for example, the user migrates data to a new device), he or she must launch the application at least once for it to receive notifications again. If the user restores backup data to a new device or reinstalls the operating system, the device token changes. Moreover, never cache a device token and give that to your provider; always get the token from the system whenever you need it
Ref: stackoverflow.com/questions/6…
31. What is the layer.cornerRadius value
Width /2, which is half the length of the square side. The corners of each corner are really a quarter circle, and the radius of the circle is a cornerRadius. The corner is a corner that is a corner that is tangent to the two sides. For a square, forming a circle is an inscribed circle. So let me draw it.Copy the code
30. Use NSJSONSerialization to analyze JSON data in a variety of complex formats.
The class method used is
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error Set different options based on the data structure. This option has three types: NSJSONReadingMutableContainers NSJSONReadingMutableLeaves, NSJSONReadingAllowFragments. The Apple documentation describes these three methods. 1, NSJSONReadingMutableContainers Specifies that the arrays and dictionaries are created as mutable Objects. // Specify arrays and dictionaries to be created as mutable objects. 2, NSJSONReadingMutableLeaves Specifies that the leaf strings in the JSON object graph are created as instances of NSMutableString.// Specifies the creation of an instance of NSMutableString in the JSON object graph string. 3, NSJSONReadingAllowFragments Specifies that the parser should allow top - level objects that are not an instance of NSArray or NSDictionary.// Specifies that the parser should allow the uppermost object not to be an array or an instance of NSDictionary.Copy the code
Available in iOS 5.0 and later.
demo: NSData *dictData2 = [@"{ \"foo\": \"bar\" }" dataUsingEncoding:NSUTF8StringEncoding]; id dict2 = [NSJSONSerialization JSONObjectWithData:dictData2 options:NSJSONReadingMutableContainers error:NULL]; NSLog(@"%@", [dict2 class]); NSLog(@"%@", [dict2 superclass]); NSLog(@"%d", [dict2 isKindOfClass:[NSMutableDictionary class]]); Output: __NSDictionaryM NSMutableDictionary 1Copy the code
NSJSONReadingAllowFragments use below parameters, to parse out. The top level object is a string.
NSString *jsonString = @"\"test\"";
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"result %@", result);
Copy the code
Ref:stackoverflow.com/questions/9…
29.UIPasteboard
The UIPasteboard class enables an app to share data within the app and with another app. To share data with any other app, you can use system-wide pasteboards; to share data with another app that has the same team ID as your app, you can use app-specific pasteboards. Apps can also create pasteboards for their own use or for use by other apps that have the same team ID. A pasteboard must be identified by a unique name. You may also mark an app-specific pasteboard as persistent, so that it continues to exist past the termination of the app and past system reboots. System pasteboards are persistent by default.
Developer.apple.com/library/ios…
28. OpenUDID:
They do NOT use the keychain, they use the UIPasteBoard, which is a shared OS construct that persists across device restarts. From the doc: “system pasteboards are persistent across device restarts, application uninstalls, and restores.”
Developer.apple.com/library/ios…
This seems to have changed, the docs now say “When a pasteboard is persistent, it continues to exist past app terminations and across system reboots. App pasteboards that are not persistent only last until the owning (creating) app quits. System pasteboards are persistent. App pasteboards by default are not persistent. A persistent app pasteboard is removed when the app that created it is uninstalled.” meaning that no pastebards survive app uninstalls. Maybe keychain is better, But I cannot find any definitive (coming from Apple) documentation about this. — Andreas Paulsson Sep 20 ’13 at 7:37
Ref:stackoverflow.com/questions/9… Stackoverflow.com/questions/1…