Objective-C and Cocoa programming Best Practices

Source: Internet
Author: User

DiscussionObjective-CAndCocoa ProgrammingThe best practice is the content to be introduced in this article. In the latest tietong in MarchProgrammingLanguage ranking,Objective-CThe share is still growing sharply, and is constantly approaching the ranks of the most popular languages.

On StackOverflow, a well-known foreign technical Q & A website, the question with the highest Objective-C tag score is "What are best practices that you use when writing Objective-C and Cocoa ?" Hao peiqiang, a senior researcher at Shanda Innovation Institute, translated the original text of the valuable answers.) after being authorized by the translator, the CSDN mobile channel reposted the full text below:

Hao peiqiang believes that these recommended items are not jinke yulv, becauseObjective-CAndCocoaThe development is very fast. I hope that every article will cause everyone to think about it and use it in their own projects after self-verification.

Some of my initial practices are not standard.

1) with property, the "_" prefix is no longer used before "private" member variables. If a member variable can be accessed by other classes, you should use property. I don't like the "_" prefix. It will make the code very ugly. Now I can use it.

2) If it is private, I tend to define methods in the. m file and put them in a private category, as shown below:

 
 
  1. #import "MyClass.h"    
  2. @interface MyClass ()   
  3. - (void) someMethod   
  4. - (void) someOtherMethod   
  5. @end    
  6. @implementation MyClass   

Why clutter up the. h file with things outsiders shocould not care about )?. The empty braces in the m file are used for private category. If you do not implement the method declared in the file, a compilation warning is triggered.

3) I put the dealloc method on the top of the. m file, next to the @ synthesize statement. What do you need dealloc? Shouldn't it be the first question when you consider a class? Especially in iPhone environments. The same is true for me. dealloc and init can be put together for comparison. The default template puts dealloc at the end, which is not conducive to comparison and easy to ignore dealloc)

In table cell, to make all elements opaque, including the cell itself ). That is to say, each item has an appropriate background color.

When using NSURLConnection, you should implement the following delegate Method

 
 
  1. - (NSCachedURLResponse *)  
  2. connection:(NSURLConnection *)  
  3. connection willCacheResponse:(NSCachedURLResponse *)  
  4. cachedResponse {        
  5.  return nil;   
  6. }   

Unless you want to cache response, you will feel that web calls are abnormal most of the time, especially web service calls. The above implementation can avoid caching any response.

4) avoid double. IPhone native does not support any double precision operations. They are simulated using libraries. Use double precision only when you must use it, for example, CoreLocation. Use the f suffix after the numeric constants so that the compiler treats them as float.

 
 
  1. float val = someFloat * 2.2f;   

More importantly, when someFloat is double, you do not need to calculate the mixed precision because val has lost the precision. Update: Some changes have taken place on 3GS, and float should be used:

Even if some mobile phones seem to have the same computing speed with different precision, float can store more data in registers, so it will be much faster. You don't have to care about it if the program is not computing-oriented .)

5) set property to nonatomic. Atomic is the default value and is synchronized. It will automatically add the synchronization code to avoid problems when multithreading occurs. However, in 99% cases, your property will not be accessed in a multi-threaded environment. Using nonatomic can avoid code bloated and improve efficiency. Note: If you want to access the property in a multi-threaded environment, remember to use atomic or lock it yourself)

6) SQLite saves large datasets very quickly. For example, the map program should cache the graph block in SQLite. The most expensive part is hard disk I/O. To avoid a large number of small writes between large blocks, you need to use BEGIN; and COMMIT ;. We use a 2-second timer to reset each new commit. Once the timer state-owned enterprises send COMMIT;, so that some operations are written into a large block. SQLLite stores transaction data on disks. Using Begin/End packaging can avoid generating a large number of Transaction files and write all transactions into one file.

When SQLite is in the main thread, it will block your interface. If you execute a very long query, a good way is to save your query as a static object and then query it in another thread. Pack all the queries that will modify the database with @ synchronize.

Short queries are placed on the main thread, which is simple and convenient. Note: The SQLite method in multithreading is simpler. Use sqlite3_open_v2 to open the database, and use SQLITE_OPEN_FULLMUTEX for flag. In this way, all SQLite functions are thread-safe and do not need synchronize, but I don't know which one is more efficient .)

More SQLite optimization techniques here, although the article is very old, it seems that they are still true:

Http://web.utk.edu /~ Jplyon/sqlite/SQLite_optimization_FAQ.html

In the past, there was no good way to manage outlet memory. The best practice is to declare outlet as property:

@ Interface MyClass: NSObject {NSTextField * textField;} @ property (nonatomic, retain) IBOutlet NSTextField * textField; @ end

Using property makes the memory management semantics clearer, and provides a unified mode for other instance variable organizations.

Note: This article is debatable. Generally, variables that do not require cross-class access are not declared as property if they are IBOutlet. This Q & A is relatively early, and there may be a lot of new information. It is mainly for your reference.

Use LLVM/Clang static analyzer:

I will not translate the original text. Recently, Xcode versions have built-in LLVM/Clang static analyzer, which is easy to use:

Xcode3 series uses the hotkey Shift + Command +

Xcode4 series uses the hotkey Shift + Command + B

To ensure the effect, it is best to clear the Build by Shift + Command + K before using the static analyzer.

Static analyzer can analyze a lot of misuse and non-standard usage, especially to help you find potential memory leakage. However, it is not omnipotent. If your code logic is messy, especially if a large number of memory management does not comply with the specifications, it may also give incorrect suggestions. The premise of its suggestion is that a large amount of your code complies with Objective-C and Cocoa specifications, and a small part of the code forgets release and so on, it will give you good suggestions.

Therefore, there will never be any fairy emperor. Writing code well is the foundation.

Standard Cocoa naming and format specifications and terms are used. The advantage of standardization is that it is more convenient to work with other Cocoa developers.

For example, what should be done and what should not be done:

* Do not declare id m_something in the interface of an object. Do not call it a member variable or field. Use something or _ something (this is not recommended now) as its name, it is called an instance variable.

* Getter should not be called-getSomething; it should be-something ;.

* Setter should not be called-something; it should be called-setSomething :.

* The method name consists of parameters and colons, such as-[NSObject into mselector: withObject:] instead of NSObject: performSelector.

* When the method name, parameter, variable, and class name consist of multiple words, the first letter of the word is capitalized, and there is no space or underline between words ).

* The first letter of the class name is in upper case, the variable name is in lower case, and the first letter of the method name is in lower case.

Do not use the Win16/Win32-style Hungarian naming method. Even when Microsoft switched to the. NET platform, it was abandoned.

Summary:Objective-CAndCocoa ProgrammingI hope this article will help you with the introduction of best practices!

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.