学过C++的朋友应该都知道 新写一个类会有 一个.h 声明类的变量 方法等 .cpp 用来实现方法 Objective-C 则也类似C++ .h 声明类的变量 方法 .m 用来实现方法
在C语言中 我们在控制台输出信息是用printf() Java语言则是 System.out.println() 而Objective-C 则是用 NSLog();
打开控制台的快捷键为 command + shift + R

- //
- // helloWorldViewController.m
- // helloWorld
- //
- // Created by 宣雨松 on 11-7-4.
- // Copyright 2011年 __MyCompanyName__. All rights reserved.
- //
- #import "helloWorldViewController.h"
- #import "MyClass.h"//导入新写的类
- @implementation helloWorldViewController
- - (void)dealloc
- {
- [super dealloc];
- }
- - (void)didReceiveMemoryWarning
- {
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use.
- }
- #pragma mark - View lifecycle
- // Implement viewDidLoad to do additional setup after loading the view, typically from a
- nib.
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- //打印一个字符串
- NSLog(@"only log hello world");
- //字符串相加
- NSString *str;
- NSString *str1 = @"plusA ";
- NSString *str2 = @"+";
- NSString *str3 = @"plusB";
- // 把str1 str2 str3 相加后赋值给str %@ 表示是一个对象 这里也可以用 %d %s 在这里就不一一举例了。
- str = [NSString stringWithFormat:@"%@ %@ %@",str1,str2,str3];
- //打印出str
- NSLog(@"string plus %@",str);
- //self 好比C++ 或者 java 语言中的 this 指针 指向本类 这里调用了本类的 putString方法 将字符串"pass string"作为参数传递了进去
- [self putString:@"pass string"];
- //在内存中new了一个MyClass的对象 alloc是在内存中 分配内存 init 则是初始化 这样写 属于规定写法
- MyClass * myclass = [[MyClass alloc] init];
- // 用myclass指针调用 类中putclass方法 将字符串 "pass class string"作为参数传递进去
- [myclass putclass:@"pass class string"];
- //调用类中静态方法 将字符串"static pass class string "作为参数传递进去
- [MyClass staticPutClass:@"static pass class string"];
- }
- - (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- // Return YES for supported orientations
- return (interfaceOrientation == UIInterfaceOrientationPortrait);
- }
- //自己写的类方法输出字符串
- -(void)putString:(NSString *)str
- {
- NSLog(@"%@",str);
- }
- @end
//这个类的声明
- #import <UIKit/UIKit.h>
- @interface helloWorldViewController : UIViewController {
- }
- -(void) putString:(NSString*)str;
MyClass类的实现
- #import "MyClass.h"
- @implementation MyClass
- //方法前是-号的说明这是一个实力方法 必需本类new过才能调用
MyClass类的声明
- #import <Foundation/Foundation.h>
- @interface MyClass :NSObject{
- }
- -(void) putclass : (NSString *) str;
这样Objective-C 基本的语法就给大家介绍完了, 希望有兴趣的朋友可以和我一起讨论 我们可以一起进步。
