如果想从事iphone开发的话 Objective-C 这门语言就不得不学会我们都知道C语言是没有面向对象的 而Object-C 则是ANSI C 的一个严格超集 它是具有面向对象的特性的 由于IPHONE 的成功让这门语言现在非常的火热 今天笔者为大家介绍一下在xcode中 使用Objective-C 的基本语法。
1.打开mac系统中强大的Xcode软件 单击Create a new Xcode project 创建一个Xcode项目。
![a](http://www.xuanyusong.com/wp-content/uploads/2012/05/a4.jpg)
2. 选择“View-based Application” 因为只是介绍基本语法 所以 “View-based Application” 已经够用了 。 选择完后 点击Next 。
![b](http://www.xuanyusong.com/wp-content/uploads/2012/05/b3.jpg)
3.输入相应的信息后点击Next。
Product Name: 指产品名称 ,可以随意命名。
Company Identifier: 公司标识符,一般命名规则为 “com.公司名”
Bundle Identifier: 指包标识符,用于唯一标识应用程序,默认会根据公司标识符和产品名来组合生成
Device Family: 指该应用支持的设备类型,共三个选项:iPhone、iPad、Universal(即iPhone、iPad通用)
Include Unite Tests: 是否包含单元测试代码模板,如果勾选,Xcode会帮助生成单元测试代码模板
![c](http://www.xuanyusong.com/wp-content/uploads/2012/05/c3.jpg)
这样 我们的第一个项目就创建好了,接下来开始为大家介绍 Objective-C 的语法
在项目视图中 打开 helloWorldViewController.m文件 找到 – (void)viewDidLoad 方法 (这个方法每次启动程序都会调用 )
学过C++的朋友应该都知道 新写一个类会有 一个.h 声明类的变量 方法等 .cpp 用来实现方法 Objective-C 则也类似C++ .h 声明类的变量 方法 .m 用来实现方法
在c语言中 我们在控制台输出信息是用printf() Java语言则是 System.out.println() 而Objective-C 则是用 NSLog();
打开控制台的快捷键为 command + shift + R
![d](http://www.xuanyusong.com/wp-content/uploads/2012/05/d2.jpg)
09 | #import "helloWorldViewController.h" |
10 | #import "MyClass.h"//导入新写的类 |
12 | @implementation helloWorldViewController |
20 | - ( void )didReceiveMemoryWarning |
23 | [super didReceiveMemoryWarning]; |
28 | #pragma mark - View lifecycle |
38 | NSLog(@ "only log hello world" ); |
42 | NSString *str1 = @ "plusA " ; |
43 | NSString *str2 = @ "+" ; |
44 | NSString *str3 = @ "plusB" ; |
46 | str = [NSString stringWithFormat:@ "%@ %@ %@" ,str1,str2,str3]; |
48 | NSLog(@ "string plus %@" ,str); |
50 | [self putString:@ "pass string" ]; |
52 | MyClass * myclass = [[MyClass alloc] init]; |
54 | [myclass putclass:@ "pass class string" ]; |
56 | [MyClass staticPutClass:@ "static pass class string" ]; |
61 | [super viewDidUnload]; |
66 | - ( BOOL )shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation |
69 | return (interfaceOrientation == UIInterfaceOrientationPortrait); |
73 | -( void )putString:(NSString *)str |
//这个类的声明
3 | @interface helloWorldViewController : UIViewController { |
7 | -( void ) putString:(NSString*)str; |
MyClass类的实现
03 | @implementation MyClass |
06 | -( void )putclass:(NSString *)str |
12 | +( void )staticPutClass:(NSString *)str{ |
MyClass类的声明
1 | #import <Foundation/Foundation.h> |
3 | @interface MyClass :NSObject{ |
6 | -( void ) putclass : (NSString *) str; |
这样Objective-C 基本的语法就给大家介绍完了, 希望有兴趣的朋友可以和我一起讨论 我们可以一起进步。