一、创建Xocode工程
1、启动Xcode,然后在File菜单下,选择New Project;
2、找到Command Line Utility大栏目,在右边的选项中选择Foundation Tool,点击choose选中;
3、在出来的savs as 提示后输入工程名,where后面选择工程将要创建的位置,点击save按钮;
4、然后你会看到一个工程建立并显示在眼前,在后缀名为.m的文件中编写我们要写的终端程序;
二、举例程序讲解
纯基础语法程序:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
1、#import关键字相当于我们认为的#include;
2、NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];在写objective-c纯语法的程序的时候,第一句都是这个,这是申请内存并且初始化,后面的[pool drain]则是释放内存,程序执行结束的意思,两者对应起来;
3、nslog函数是一个输出函数,在C语言函数中相当于是一个printf的功能函数;
Iphone开发基于windows的程序:
在new project的时候选择Application,然后选中Windows-based Application,自动生成工程后,看到其中两个文件,分别为.h,.m:
.h文件
//
// testAppDelegate.h
// test
//
// Created by MeMac.cn on 11-8-11.
// Copyright __MyCompanyName__ 2011. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface testAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
1、NSObject这个是基类,所有的类都直接或者间接继承于这个类,后面<UIApplicationDelegate>是协议,一般用委托的时候要用到,内容在iphone开发中提及,这里一笔带过;
2、@property和后面的.m文件中的@synthesize一起用声明了一个对象的输出口,而且这个对象的数值自动增设了一个获取和一个赋值的函数,至于IBOutlet输出口的定义可以在类里面,不一定要在@property后面;
3、Nonatomic它要与@synthesize一起使用才有意义。 atomic的意思就是setter/getter这个函数是一个原语操作。如果有多个线程同时调用setter的话,不会出现某一个线程执行setter全部语句之前,另一个线程开始执行setter情况,相当于函数头尾加了锁一样。 nonatomic不保证setter/getter的原语行,所以你可能会取到不完整的东西。 比如setter函数里面改变两个成员变量,如果你用nonatomic的话,getter可能会取到只更改了其中一个变量时候的状态;
4、retain这个位置其实还可以填写为copy和resign,这里写retain相当于是一个引用的意思,这个和后面的内存释放有关系,因为在iphone中没有垃圾自动回收机制,所以内存问题也就是重中之重。
.m文件
//
// testAppDelegate.m
// test
//
// Created by MeMac.cn on 11-8-11.
// Copyright __MyCompanyName__ 2011. All rights reserved.
//
#import "testAppDelegate.h"
@implementation testAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
1、 第一个函数是程序加载时调用,一般对于window主窗口加载子视图、组件一类的都写在这个位置;
2、 第二个函数是内存回收函数,当程序退出的时候,@synthesize这个关键字后的变量一定要在这个函数中释放,这个和retain这个关键字的引用也有关系,程序不能自动释放他的内存,因此我们必须手动来释放这些内存资源。