Some common method notes for IOS

Source: Internet
Author: User

Global References:
BOOL State
Other places: extern BOOL State;
Two special cases:
@synthesize id=_id;
@synthesize descriptoin=_description;
The difference between _ and self:
There are setter and Getter methods (@property (nomatic, Passion) UIView *view) when both plugs are available,
When only the attribute ({e.g.: UIView *_view}) is only "_"


Retain is a pointer copy and copy is a copy of the content.
Tells the compiler to generate the Getter/setter method during compilation by using the @synthesize directive. 2: Implement the method by @dynamic instructions.
Location Request Authorization: Nslocationwheninuseusagedescription or Nslocationalwaysusagedescription


1.mrc.arc:
Using Arc-fobjc-arc under the 2.MRC compilation environment
Conversely:-fno-objc-arc
3.init methods, initialization and shared methods
4. To use local variables within block blocks, you need to add "__block variable name" outside the Block
5.
1.//Get the documents directory for the application sandbox Nsarray *paths=nssearchpathfordirectoriesindomains (nsdocumentdirectory,nsuserdomainmask , YES);
2. NSString *plistpath1 = [Paths objectatindex:0];
3.
4.//Get the full filename
5. NSString *filename=[plistpath1 stringbyappendingpathcomponent:@ "Test.plist"];
6.//Input Write
7. [Data writetofile:filename Atomically:yes];
8.
9.//How does it prove that my data is written? Read it and see.
Nsmutabledictionary *data1 = [[Nsmutabledictionary alloc] initwithcontentsoffile:filename];
NSLog (@ "%@", data1);
12.
13.
14. @ (20): This represents an object
15. Abstract class: Used to derive subclasses
#define If the definition is too long to add "\" when the line breaks
Frame refers to the position and size of the view in the parent view coordinate system. (The reference point is the father's coordinate system) bounds refers to the position and size of the view in its own coordinate system. (The reference point is its own coordinate system)
18. Redraw Setneedsdisplay, call DrawRect, refresh layout: setneedslayout, call Layoutsubviews,

Set two properties in target when the call is positioned: nslocationalwaysusagedescription nslocationwheninuseusagedescription
The workaround for HTTP access is not supported after Xcode upgrade: Add nsapptransportsecurity type dictionary in Info.plist.
Add Nsallowsarbitraryloads type Boolean under Nsapptransportsecurity with the value set to Yes

1. Send SMS
If you use this method to send text messages, the app will not be returned after the SMS is sent or canceled
Nsurl *url = [Nsurl urlwithstring:@ "sms://10010"];
[[UIApplication sharedapplication] openurl:url];

Determine if the current device can send text messages
if (![ Mfmessagecomposeviewcontroller Cansendtext]) {
NSLog (@ "Current device cannot send SMS");
return;
}

Mfmessagecomposeviewcontroller *VC = [[Mfmessagecomposeviewcontroller alloc] init];
Set SMS Content
Vc.body = @ "Have you eaten yet?" ";
Set up a recipient list
vc.recipients = @[@ "10010"];
Set up Proxy
Vc.messagecomposedelegate = self;
Display Controller
[Self PRESENTVIEWCONTROLLER:VC animated:yes completion:nil];

2. Call

Cons: After dialing with this method, the phone will not return to the application when it hangs up and will stay in the call log interface
Nsurl *url = [Nsurl urlwithstring:@ "tel://13261936021"];
[[UIApplication sharedapplication] openurl:url];

When a call is made, the user is prompted for a call, and the application is returned when the phone hangs up
Nsurl *url = [Nsurl urlwithstring:@ "telprompt://13261936021"];
[[UIApplication sharedapplication] openurl:url];

3. Bubble Sorting algorithm

for (i = 0; i < length-1; ++i)//times?
{  ?
for (j = i + 1; j < length; ++j)?
{  ?
if (Arr[i] > Arr[j])?
{  ?
TMP = Arr[i]; ?
Arr[i] = Arr[j]; ?
ARR[J] = tmp; ?
}  ?
}  ?
}

4. Picture stretching from the middle
Left cover width
Nsinteger leftcapwidth = bgImage.size.width * 0.5f;
Top cover Height
Nsinteger topcapheight = bgImage.size.height * 0.5f;

Bgimage = [Bgimage stretchableimagewithleftcapwidth:leftcapwidth topcapheight:topcapheight];

5. Pop-up animations
Factory animation
-(void) Animationwith: (UIView *) view
{

cakeyframeanimation* animation = [Cakeyframeanimation animationwithkeypath:@ "transform"];
Animation.duration = 0.5;

Nsmutablearray *values = [Nsmutablearray array];
[Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (0.1, 0.1, 1.0)];
[Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (1.2, 1.2, 1.0)];
[Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (0.9, 0.9, 1.0)];
[Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (1.0, 1.0, 1.0)];
Animation.values = values;
[View.layer addanimation:animation Forkey:nil];


}

6. Frequently error-prone and missing places
You must set the tag value to be greater than 0, and the TableView can not be set to the top and the top height. It could be 0.001.
7.
Handle keyboard Popup Events to adjust the height of the search box
-(void) registnoti{

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (shown:) Name: Uikeyboardwillshownotification Object:nil];

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (keyboardhidden:) Name: Uikeyboardwillhidenotification Object:nil];



}

Keyboard display
-(void) shown: (nsnotification*) notification
{
Keyboardframe
CGRect initialframe = [[[Notification UserInfo] objectforkey:uikeyboardframeenduserinfokey] cgrectvalue];

CGRect convertedframe = [Self.view convertrect:initialframe fromview:nil];

CGRect tvframe = self.infoTabaleView.frame;
TvFrame.size.height = convertedframe.origin.y-60;
Self.infoTabaleView.frame = Tvframe;

}

Keyboard Hide
-(void) Keyboardhidden: (nsnotification*) notification
{
CGRect tvframe = self.infoTabaleView.frame;
TvFrame.size.height = _initialtvheight;
Self.infoTabaleView.frame = Tvframe;
}


Clean up the cache
Uialertview * Alert =[[Uialertview alloc]initwithtitle:@ "Prompt" message:@ "Whether to delete cache" Delegate:self cancelbuttontitle:@ "OK" otherbuttontitles:@ "Cancel", nil];

NSString * documentpath =[nsstring stringwithformat:@ "%@/documents", Nshomedirectory ()];
NSLog (@ "%@", documentpath);
BOOL Isdataexist=[[nsfilemanager Defaultmanager]fileexistsatpath:documentpath];
NSLog (@ "~~~~~~~%d", isdataexist);
if (isdataexist)
{
Long long Content=[[[nsfilemanager Defaultmanager]attributesofitematpath:documentpath error:nil]filesize];
float size=content/1024.0;
NSString * Content2 = [NSString stringwithformat:@ "%.2FMB", size];
Alert.message = [@ "Whether to delete cache" Stringbyappendingstring:content2];
[[Nsfilemanager Defaultmanager]removeitematpath:documentpath Error:nil];
[Alert show];
}
Else
{
Alert.message = @ "no cache";
[Alert show];
}

Picture cropping: For example, when the star is displayed:
Starimageview.contentmode=uiviewcontentmodeleft;
Set Trim
Starimageview.clipstobounds=yes;
float X=65/5.0*num;
Starimageview.frame=cgrectmake (0, 0, X, 23);

To determine the version number:
NSString *key = @ "Cfbundleversion";

Remove the version number of the last-used software stored in the sandbox
Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];
NSString *lastversion = [defaults stringforkey:key];

Get the version number of the current software
NSString *currentversion = [NSBundle Mainbundle].infodictionary[key];

if ([CurrentVersion isequaltostring:lastversion]) {
Show status bar

} else {//new version
[Defaults setobject:currentversion Forkey:key];
[Defaults synchronize];
}


Get pictures based on color
-(UIImage *) Imagewithcolor: (Uicolor *) color
{
CGRect rect = CGRectMake (0.0f, 0.0f, 1.0f, 1.0f);
Uigraphicsbeginimagecontext (rect.size);
Cgcontextref context = Uigraphicsgetcurrentcontext ();

Cgcontextsetfillcolorwithcolor (context, [color Cgcolor]);
Cgcontextfillrect (context, rect);

UIImage *image = Uigraphicsgetimagefromcurrentimagecontext ();
Uigraphicsendimagecontext ();

return image;
}
The picture on the current view
+ (UIImage *) Captureimagewithview: (UIView *) view
{
1. Create a bitmap context
Uigraphicsbeginimagecontext (view.frame.size);
2. Draw the layer of the view you want to save into the bitmap context
[View.layer Renderincontext:uigraphicsgetcurrentcontext ()];
3. Remove the picture of the drawing number
UIImage *newimage = Uigraphicsgetimagefromcurrentimagecontext ();
return newimage;
}

1. Modify copy and paste display in English
/*
How to modify the system language display in English (copy, paste)
The solution is to use VIM to open the project's Info.plist file directly, add the following content in the file
<key>CFBundleLocalizations</key>
<array>
<string>zh_CN</string>
<string>en</string>
</array>

*/
Another way: Modify the localization of the Info.plist file native Development Region property value is China
2. Image compression
+ (uiimage*) Imagewithimagesimple: (uiimage*) Image scaledtosize: (cgsize) newSize
{
Create a graphics image context
Uigraphicsbeginimagecontext (newSize);
Tell the old image to draw in this new context, with the desired
New size
[Image Drawinrect:cgrectmake (0,0,newsize.width,newsize.height)];
Get the new image from the context
uiimage* newimage = Uigraphicsgetimagefromcurrentimagecontext ();
End the context
Uigraphicsendimagecontext ();
Return the new image.
return newimage;
}
3.javascript
<1> get the URL of the current page
NSString *currenturl = [WebView stringbyevaluatingjavascriptfromstring:@ "Document.location.href"];
NSLog (@ "Currenturl =%@", currenturl);

<2> gets the title of the current interface
NSString *title = [WebView stringbyevaluatingjavascriptfromstring:@ "Document.title"];
NSLog (@ "title =%@", title);

4. When the program starts, each time you receive a push or the program does not start by pushing the message to start the program, it will trigger the method inside the Appdelegate (note that the certificate with the server has been, such as the development environment, the server will also use the development certificate of the PEM line):
-(void) Application: ( UIApplication *) Application didreceiveremotenotification: ( Nsdictionary *) UserInfo
{
Here is the logic code after the push is received
Need #import <AudioToolbox/AudioToolbox.h>
Audioservicesplaysystemsound (1007); Notification sound of the system
Audioservicesplayalertsound (ksystemsoundid_vibrate);//Vibration
Custom sounds
NSString *path = [[NSBundle mainbundle] Pathforresource: @ "message" OfType: @ "wav"];
Assemble and play sound effects
Systemsoundid Soundid;
Nsurl *filepath = [Nsurl fileurlwithpath:p Ath Isdirectory:no];
Audioservicescreatesystemsoundid ((__bridge cfurlref) FilePath, &soundid);
Audioservicesplaysystemsound (Soundid);
Sound stop
Audioservicesdisposesystemsoundid (Soundid);
}
* UserInfo default contains the following content:
APS = {
alert = "";//push to display the problem information here
Badge = 0;//app The push number in the upper right corner of the icon is set here
Sound = "";
};
* If you need to add a custom field, let the server's small partners add an array to the same level as the APS (in JSON, for example):
{
"APS": {"alert": "This was the alert text", "badge": 1, "sound": "Default"},
"Server": {"ServerID": 1, "name": "Server Name")
}
Received this way.
There will be one more server field in UserInfo.

Some common method notes for IOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.