Developing iOS applications using MonoTouch in Visual Studio: development experience

Source: Internet
Author: User

Create a project

According to my personal habits, I will first create a blank solution. Open MonoDevelop in Mac OS X, select File-New-Solution from the menu, select the Blank Solution template in the Other category in the pop-up dialog box, and enter the appropriate location and name:

Then, create an iPhone application project. In the dialog box, select the iPhone Window-based Project template under the C #-iPhone and iPad categories. Similarly, fill in the appropriate location and name at the bottom of the dialog box. My habit is to put all the source code under the src directory (A src directory will also be created in the solution ):

Click OK. The next step is the additional project configuration. You can click OK. In this case, we will find the project file shown in MonoDevelop:

Main. cs contains the project startup code and an AppDelegate class, MainWindow. xib is the interface file of the Main Window, while MainWindow. xib. designer. the cs file is the C # code automatically created by MonoDevelop Based on the mark in the xib file. In most cases, we will not modify it.

Editing page

Double-click the MainWindow. xib file to open Interface Builder. The left is the Library window (similar to the Toolbox in VS); the top is the visual UI editor, and the bottom is the object manager, showing the objects defined in the interface; the right side is the Inspector window for modifying Properties (similar to the Properties window in ):

First, select Objects at the top of the Library window, drag a Round Rect Button to the UI Editor, double-click, and enter Hello World:

Then, select Classes at the top of the Library window, select AppDelegate in the list above, select Outlets in the drop-down box below, and add an id using the plus sign below, called ButtonCounter:

Next is an interesting operation. Select the App Delegate object in the object manager, select Connections above the Inspector, and then drag the dot on the Right of ButtonCounter to the button. This will associate the ButtonCounter id with the button, for example:

Save in Interface Builder, return to MonoDevelop, open the MainWindow. xib. designer. cs file, and you can see the ButtonCounter attribute generated in AppDelegate:

  1. private MonoTouch.UIKit.UIButton __mt_ButtonCounter; 
  3. [MonoTouch.Foundation.Connect("ButtonCounter")] 
  5. private MonoTouch.UIKit.UIButton ButtonCounter { 
  7. get { 
  9. this.__mt_ButtonCounter = ((MonoTouch.UIKit.UIButton) 
  11. (this.GetNativeField("ButtonCounter"))); 
  13. return 
  15. this.__mt_ButtonCounter; } 
  17. set { this.__mt_ButtonCounter = value; 
  19. this.SetNativeField("ButtonCounter", value); 
  21. }} 

It can be seen that MonoDevelop automatically generates some C # code based on the xib content. AppDelegate is a Partial Class, and its other part is in the Main. cs file. We will use the ButtonCounter definition here later.

Configure Visual Studio. Although the sln and csproj file formats of MonoDevelop are compatible with Visual Studio (including VS in versions 2005, 2008, and 2010 ), however, VS cannot identify the project template of the iPhone application. Therefore, loading fails if you open iOS101.sln directly. Therefore, we need to create some sln and csproj in parallel. Most of the content is synchronized with the content created by MonoDevelop.

For example, I created iOS101.VS. sln and iPhoneApp. UI. VS. csproj (.. NET 2.0 Class Library, which is different from iOS101.sln and iPhoneApp. UI. csproj is placed in the same directory. It is worth noting that the iPhone app. UI. VS. csproj file. If you directly create this project file in VS, its default namespace will also contain "VS", you may need to manually modify it. To be consistent with the project in MonoDevelop, we also need to reference the dll provided by MonoTouch SDK. So I created the lib/monotouch directory in the iOS101 directory and used the following command to copy all dll files provided by MonoTouch:

Cp/Developer/montouch/usr/lib/mono/2.1/*. dll ~ /Projects/iOS101/lib/monotouch and then edit the Assembly reference of iPhone App. UI. VS. csproj and the project file. The final result is similar to this. Note that the xib file type in MonoTouch is Page, while in VS, it must be set to None:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <Project ...> ... 
  3. <ItemGroup> 
  4. <Reference Include="monotouch"> 
  5. <HintPath>..\..\lib\monotouch\monotouch.dll</HintPath> 
  6. </Reference> 
  7. <Reference Include="System"> 
  8. <HintPath>..\..\lib\monotouch\System.dll</HintPath> 
  9. </Reference> 
  10. <Reference Include="System.Core"> 
  11. <HintPath>..\..\lib\monotouch\System.Core.dll</HintPath> 
  12. </Reference> 
  13. </ItemGroup> 
  14. <ItemGroup> 
  15. <None Include="Info.plist" 
  16. /> 
  17. <Compile Include="Main.cs" 
  18. /> 
  19. <None Include="MainWindow.xib" 
  20. /> 
  21. <Compile Include="MainWindow.xib.designer.cs"> 
  22. <DependentUpon>MainWindow.xib</DependentUpon> 
  23. </Compile> 
  24. </ItemGroup> 
  25. ...</Project> 

The result in VS is similar:

After compilation, the configuration is successful.

Write code

Are you wondering why the. NET 2.0 project was created above? Can we still use the advanced features in C #3.0? The answer is yes. If we use Visual Studio 2008 or 2010. NET 2.0 code, VS will also use the C #3.0 compiler, because we all know that C #3.0 only requires a little support for the framework and class library (Extension Method ). You can even use some features of C #4.0, such as the default values of parameters and named parameters. Unfortunately, you cannot use the dynamic nature of C #4.0, because it requires DLR and Microsoft. CSharp. dll, and involves a large amount of dynamic code generation. I have no confidence or willingness to do so. If you are interested, try again.

The reason why I use. NET 2.0 here is that I want to minimize the dependency on the system assembly and try to use the dll provided by MonoTouch. For example, in addition to mscorlib, all the Assemblies have nothing to do with the. NET Framework installed on Windows. This ensures that the code we write can be compatible with MonoTouch.

Now let's start writing code. You can open Main. cs in VS and add the following code to the FinishedLaunching method of AppDelegate to make it:

  1. public 
  3. override 
  5. bool FinishedLaunching(UIApplication app, NSDictionary options){ 
  7. int i = 
  9. 0; 
  11. this.ButtonCounter.TouchDown += 
  13. delegate 
  16. this.ButtonCounter.SetTitle((++i).ToString(), UIControlState.Normal); 
  18. }; 
  20. window.MakeKeyAndVisible(); 
  22. return 
  24. true;} 

The FinishedLaunching method is called when the program starts. In this case, we add a TouchDown event (similar to Click) to the ButtonCounter to add a handler. The anonymous function feature in C # is used here, and the external variable I is captured. Each time you click the button, I is added and displayed on the button. Here, we use. NET to add event processing in a common way. In fact, you can also define an Action in Interface Builder and associate it with the TouchDown event of the Button. This Action is represented as a Partial Method. You can complete its implementation in the code.

After saving the code, you can return to MonoDevelop. To be able to run in the iPhone simulator, You need to modify a parameter. Right-click the iPhone App. UI, open the Options dialog box, select the Build-iPhone Build category on the left, and set the SDK version on the right to 4.0, as shown below:

Click OK to save and close the dialog box. You can choose Run-Run from the menu, or directly use the shortcut key Command (Win key) + Alt + Enter to compile the project and open the simulator execution program. You can select iPhone 4 or iPhone 4 in Hardware-Device. The running effect is as follows:

Click the button to view the effect.

Unit Testing and others

To Debug the code, you only need to set the endpoint in MonoDevelop and select Run-Debug from the menu, or directly use the shortcut key Command + Enter to Debug the simulator. But what if it is a unit test? This is not a problem. MonoDevelop comes with a NUnit project. You can create such a unit test project, delete its default reference, and replace it with the Assembly provided by MonoTouch SDK, you can also develop unit test code in Visual Studio, but the debugging must be performed in MonoDevelop, because MonoTouch provides Mono implementation in Mac, in Windows, they only provide the necessary metadata for Visual Studio, so that we can enjoy the convenience of smart prompts and so on. It is impossible to run in Windows.

However, in fact, we can also define projects in Visual Studio.. NET Framework 3.5 project, and directly use. NET, for the additional assembly in MonoTouch, such as System. json. dll. NET 3.5 can be re-built by yourself (source code can be used. NET Reflector to obtain or use the open source code on Mono ). The advantage of this is that we can debug and test all MonoTouch-independent code in Visual Studio. Therefore, we can stay in the familiar and powerful environment as much as possible in the code development stage, which is of great help to the development efficiency.

This method also has disadvantages, for example, although the class library provided by MonoTouch and. NET 3.5 compatibility, but in fact I cannot guarantee this, so in. NET 3.5 can be compiled through the Code, or may not be able to compile and execute in MonoTouch. In addition, this method also prevents you from using the Mono program to centralize the extension of. NET (mainly the class library under the Mono namespace ). However, these two theoretical problems have not caused me any problems so far, and I have returned to Mac and MonoDevelop only when I need to view the running effect of the simulator.

Some friends may be familiar with System. Json because it also appears in Silverlight development. You are right. In fact, the version number of the Assembly in MonoTouch is the same as that in Silverlight, both and even strong signatures are consistent. Unfortunately, the class library in Silverlight is a subset of. NET 3.5. For example, all synchronous I/O operations are excluded, so it is difficult for us to use Silverlight to develop MonoTouch programs. Of course, with Silverlight, it is also helpful for us to develop MonoTouch. This will be discussed later.

Finally, you should have realized that we need to directly synchronize the VS project file with the MonoDevelop project file, which includes Assembly reference and code file. If you think manual editing is troublesome, write a small program for automatic synchronization-no? So don't start with MonoTouch. Start with the basics of programming.

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: 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.