轉自: http://blog.liuhongwei.cn/iphone/objective-c/php
進軍iPhone開發,最大的難點之一就是怪異的Objective C語法了。不過,瞭解以後才發現,原來僅僅是形式上與C++、Java有差別,屬於換湯不換藥。若是有C語言基礎,又用過C++、Java,2天以內掌握Objective C,沒有問題,至少看例子程序會感受順眼不少。html
Objective C脫胎於C語言,蘋果版的開發編譯環境就是大名鼎鼎的Xcode,其中的Cocoa就是Objective C庫函數。objective-c
int main( int argc, const char *argv[] ) { printf( "hello worldn" ); return 0; }
#import <Foundation/NSObject.h> @interface Bank: NSObject { NSString *name; int amount; } -(void) print; -(void) addAmount: (int) a; -(int) amount; -(Bank *) initWithName: (NSString *) n andAmount: (int) a; @end
#import "Bank.h" #import <Foundation/NSObject.h> #import <Foundation/NSString.h> @implementation Bank -(void) print { printf("Total amount is %i", amount); } -(void) addAmount: (int) a { amount += a; } -(int) amount{ return amount; } -(Bank *) initWithName: (NSString *) n andAmount: (int) a{ self = [super init]; name = n; amount = a; return self; } @end
#import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import "Bank.h" int main( int argc, const char *argv[] ) { //建立新對象,使用缺省初始化函數 Bank *bankDefault = [[Bank alloc] init]; //建立新對象,使用自定義初始化函數 Bank *bank = [[Bank alloc] initWithName: @"Harry" andAmount: 28]; [bank addAmount: 1]; [bank print]; [bank free]; // 釋放對象 [bankDefault free]; // 釋放對象 return 0; }