New Year's Day, inventory some app development skills

Source: Internet
Author: User
Tags time 0

This article reprinted to http://www.cocoachina.com/ios/20150114/10912.htmllooking back at what happened to us over the past year, one thing has to be said: 2014 is an incredible year for Apple developers. There have been so many changes in this short year (about app development): in front of the attractive swift, we almost forget how obsessed with objective-c, and the imaginative iOS 8 and watchkit, it's hard to imagine what API can compare with it.

Nshipster's practice: Please lovely children's shoes, on the first day of the New Year, to show you (in development) often used techniques and methods. Now, with the emergence of a series of APIs from Cupertino (Cupertino, Apple Headquarters, San Francisco) and many open source communities, MOM will never have to worry that we can find something interesting to share!

Here, we thank the following children's shoes for their contributions:

Colin Rofls, Cédric Luthi, Florent Pillet, Heath Borders, Joe Zobkiw, Jon friskics, Justin Miller, Marcin Matczuk, Mikael Konradsson, Nolan O ' Brien, Robert Widmann, Sachin Palewar,samuel Defago, Sebastian wittenkamp, Vadim Shpakovski, and Zak

Tips for using member functions
(from Robert Widmann)

When you invoke a member function in a swift class and struct statically, you typically use the following format:

object-> (parameter)->things

For example, you can call reverse () in one of the following two ways:

12 [1,2,3,4].reverse( )Array.reverse([1,2,3,4])

Encapsulate C strings with @ ()
(from Samuel Defago)

In fact, most of the time the text is a collection of numbers and letters, using the C string, especially when I use runtime encoding, I often forget to use UTF8 encoding, NULL end: Objective-c string Encapsulation:

123 NSString *propertyAttributesString =    @(property_getAttributes(class_getProperty([NSObject class], "description")));// [email protected]"NSString",R,C

Amibeingdebugged

Nolan O ' Brien in this Q&a technical document lets us notice the Amibeingdebugged function method:

Using deferred store properties
(from Colin Rofls)

In the development process, you should avoid using the optionals type, and you should not use an implicit unpacking optionals type. Do you want to declare a var variable but don't want to give an initial value? Use "lazy", the only thing to note is: Do not call the Getter method before your property is assigned (Fair Trade!). )

1 lazy varsomeModelStructure = ExpensiveClass()

If you only call the Set method on the var variable and do not invoke the Getter method, the lazy-modified VAR variable will not be assigned a value. For example, it would be appropriate to use lazy to modify the views variables that are not initialized until viewdidload.

Get the child view controller in the storyboard view container
(from Vadim Shpakovski)

There is a convenient way to get the child view controller in the Storyboard view container:

123456789101112131415161718192021222324 // 1. A property has the same name as a segue identifier in XIB@property (nonatomic) ChildViewController1 *childController1;@property (nonatomic) ChildViewController2 *childController2;// #pragma mark - UIViewController- (void)prepareForSegue:(UIStoryboardSegue *)segue                 sender:(id)sender{    [superprepareForSegue:segue sender:sender];    // 2. All known destination controllers assigned to properties    if([self respondsToSelector:NSSelectorFromString(segue.identifier)]) {        [self setValue:segue.destinationViewController forKey:segue.identifier];    }}- (void)viewDidLoad {    [superviewDidLoad];    // 3. Controllers already available bc viewDidLoad is called after prepareForSegue    self.childController1.view.backgroundColor = [UIColor redColor];    self.childController2.view.backgroundColor = [UIColor blueColor];}

Run the project repeatedly without repeating the build project
(from Heath Borders)

If you are constantly debugging the same problem, you can run your app without repeating the build, so: "Product>perform Action>run without Building" (shortcut key?? R:command + R)

Quick access to playground resources
(from Jon friskics)

All Playground in Swift share the same data directory:/users/home/documents/shared Playground

If you prefer to use many playgrounds, you will need to create a new subdirectory for each playground in the above shared directory to store the data used by each playground But then you need to tell each playground where to get its corresponding data. Here's a secondary workaround that I often use:

123 func pathToFileInSharedSubfolder(file: String) -> String {    returnXCPSharedDataDirectoryPath + "/" + NSProcessInfo.processInfo().processName + "/"+ file}

The ProcessName property is the name of the playground file, so as long as you have created a new subdirectory under the same name in the Playground data sharing file directory, you can easily access the data as well as read the local JSON data:

123 varjsonReadError:NSError?let jsonData = NSFileManager.defaultManager().contentsAtPath(pathToFileInSharedSubfolder("data.json"))!let jsonArray = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &jsonReadError) as [AnyObject]

.... Or visit a local picture

12 let imageView = UIImageView()imageView.image = UIImage(contentsOfFile: pathToFileInSharedSubfolder("image.png"))

-----------------------------------------------------------------------

Please attention! The remainder of this article comes from the contribution of Cédric Luthi, who has shared some of the more useful development techniques and techniques that are sufficiently self-sufficient to read. Here again Thanks cédric!

Cocoapods Big Secret

Here's a quick way to check all the pods that are used in the app:

1 $ class-dump -C Pods_ /Applications/Squire.app | grep -o "Pods_\w+"

Create_infoplist_section_in_binary

Note the Create_infolist_section_in_binary property that is set for the Command mode app (command-line apps) in Xcode. This is easier than using the-sectcreate__text__info_plist link flag bit, which also embeds the compiled Info.plist file into the binary encoding.

It also gave us a lesson on how to ask for Apple, a feature that was rdar://4722772 in 2006, but was not met until 7 years later.

(Translator Note: The implication is that it is a negative, should be more skillful to ask for demand)

Disable Dylib Hooks
(from Sam Marshall)

Sam Marshall The trick is to go his own way, so that hackers have no way to go.

Add the following line to your "other Linker Flags":

1 -Wl,-sectcreate,__RESTRICT,__restrict,/dev/null

Nsbundle-preferredlocalizations

At some point, you need to know what language the app is currently using. Usually, you will use Nslocal+preferredlanguages. Unfortunately, this method does not tell you what the app actually renders in the text language. You will only get the option in the "Settings->general->language&region->preferred Language" list on the iOS system, or the OS Preferences->language & region->preferred Languages The options in the list. Imagine: the list of preferred languages is only {English, French}, but your app only uses German, and calling [[[Nslocal Preferredlanguages] Firstobject] returned to you is English, not German.

The correct approach is to use the [[NSBundle Mainbundle] preferredlocalizations] method.

Apple's development documentation says this:

An array of NSString objects containing the language IDs localized in the bundle, in which the string ordering is based on the user's language preferences and the geographic location that can be used.

Notes in NSBundle.h:

A localized subset of bundles, reordered into the priority sequence of the current execution of the bad, the first in the language order of the main bundle is the languages that the user wants to see on the UI interface.

Of course you may need to call this method:

1 NSLocal+canonicalLanguageIdentifierFromString:

To make sure that the language you are using is a standard language.

Protect SDK Header files

If you install Xcode with DMG, take a look at this article Joar Wingfors, which tells you how to avoid accidentally modifying the SDK header file by preserving ownership:

1 $ sudo ditto /Volumes/Xcode/Xcode.app /Applications/Xcode.app

Any type of instance variable detection

To achieve the purpose of reverse processing, querying the object's instance variables is a common and reliable way. It is common to call the object Valueforkey: method to do this, except for a few classes that override the class method +accessinstancevariablesdirectly to mask the operation.

Here's an example: When an instance variable has an attribute of any type, the operation mentioned above is invalid

This is a reference to the MediaPlayer framework in the iOS6.1 SDK:

1234 @interface MPMoviePlayerController : NSObject {    void *_internal;    // 4 = 0x4    BOOL _readyForDisplay;  // 8 = 0x8}

Because ID internal=[movieplayercontroller valueforkey:@ "internal" is invalid, here's a stupid way to get this variable:

1 id internal = *((const id*)(void*)((uintptr_t)moviePlayerController + sizeof(Class)));

Attention! Do not call this code arbitrarily, because the layout of the Ivar may change (the pointer offset calculation may be wrong). Use only in reverse engineering!

NSDateFormatter +dateformatfromtemplate:options:locale:

Tip: If you call [NSDateFormatter Setdateformat] and don't call [NSDateFormatter dateformatfromtemplate:options:local:],n then it's likely to go wrong.

Apple Documentation:

123 + (NSString *)dateFormatFromTemplate:(NSString *)template                             options:(NSUInteger)opts                              locale:(NSLocale *)locale

Different regions have different date formats. The purpose of using this method is to get a suitable format for the specified date field in the specified region (usually you can view the current region by Currentlocal)

The following example shows us the different date formats for British English and American English:

1234567891011121314151617 NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];NSString *dateFormat;NSString *dateComponents = @"yMMMMd";dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];NSLog(@"Date format for %@: %@",    [usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];NSLog(@"Date format for %@: %@",    [gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat); // Output:// Date format for English (United States): MMMM d, y// Date format for English (United Kingdom): d MMMM y

Get internal constants through debugging

Recently, Matthias Tretter asked on Twitter:

Does anyone know the default animation time and jump mode of modal Viewcontroller presentation in iOS8?

We found such a function in the Uikit class library: [Uitransitionview defaultdurationfortransition:], and add a breakpoint at the location of the method:

1 (lldb) br set -n "+[UITransitionView defaultDurationForTransition:]"

Modal displays a viewcontroller that stops at this breakpoint and enters finish to execute the method:

1 (lldb)finish

In Defaultdurationfortransition: When executed, you will be able to read the results (in the XMM0 register)

12 (lldb) register read xmm0 --format float64    xmm0 = {0.4 0}

Reply: Default animation time 0.4s

DIY Weakly associative objects

Unfortunately, the association object Objc_association_assign policy does not support weak references with a reference count of 0. Fortunately, you can easily implement it, you just need a simple class and weakly reference an object in this class:

12345678910111213141516 @interface WeakObjectContainter : NSObject@property (nonatomic, readonly, weak) id object;@end@implementation WeakObjectContainter- (instancetype)initWithObject:(id)object {    self = [superinit];    if(!self) {        returnnil;    }    self.object = object;    returnself;}@end

The weakobjectcontainter is then associated with Objc_association_retain (_nonatomic):

1 objc_setAssociatedObject(self, &MyKey, [[WeakObjectContainter alloc] initWithObject:object], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

Use the object property to point to this weak reference object that requires a reference count of 0.

1 id object = [objc_getAssociatedObject(self, &MyKey) object];

With so many new technologies moving forward, we will usher in a year full of possibilities and opportunities. In this, I wish you a happy New Year 2015!

Willing to program on the road, with June encouragement.
(This article is for Cocoachina organization translation, this translation right belongs to the translator, without permission to prohibit reprint.) )

New Year's Day, inventory some app development skills

Related Article

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.