Objective-C的基本语法

来源:互联网 发布:编程数学要求高吗 编辑:程序博客网 时间:2024/04/30 18:53

文章来源:http://blog.sina.com.cn/s/blog_7fa6b06f01011a3f.html

1,Objective-C 2.0语法简介

     1,OC的Hello World!
#import <Foundation/Foundation.h>
 
int mian(int argc, const char * argv[])
{
     NSLog(@"Hello World!");
    
     return 0;
}
         注解:使用#import可以智能包含头文件,不需要我们再写那些防止头文件重复包含的宏(是为了防止重复定义)。在用#import的时候不要混用#include。"Hello World!"是以字符数组的形式存放在数据段。
     2,语法纵览:
         Objective-C是C语言的面向对象的一个超集。和C++不同,Objective-C最初只是为了给C设计一款最小化的面向对象的语法。同时完全兼容C语言。当然现在也兼容C++。为了避免和已有的C,C++关键字冲突。所有的O-C(以后都统称为O-C)关键字都有@开始,比如:@class,@interface,@implementation,@public,@private,@protected,@try,@catch,@throw,@finally, @end,@protocol,@selector,@synchronized,@encode,@defs。O-C2.0引入的关键字:@optional,@required,@property,@dynamic,@synthesize。
     3,一些对比:
         C/C++和O-C一样,都是用如下:和//做注释。
         BOOL YES, NO
              typedef signed char BOOL;
              在C++中,布尔类型是bool,在O-C中,布尔类型是BOOL,布尔值有YES和NO两种。
         id类型
              O-C中,每个目标都可以表达为id类型,可以认为是一个泛型。类似于C语言中的void *。
         nil
              #define nil NULL
              nil等同于NULL,表示一个目标的指针,但是nil和NULL不是完全等同的,不能相互帖。
              nil修饰的是OC对象,NULL是普通的C语言指针。
         Nil
              对于类指针类说,nil和Nil一样。
demo1
#import <Foundation/Foundation.h>
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
     NSLog(@"Hello, World!");
     NSLog(@"1 + 1 = %d", 1 + 1);
     NSLog(@"%d", (int)4.3);
     BOOL flag = 0xff10;
     id ptr = nil;
     NSString * str = nil;
     if (flag) {
         NSLog(@"Yes");
     }else {
         NSLog(@"No");
     }
    
     [pool drain];
 
    return 0;
}
2,类和继承
     1,C++类格式
         文件Foo.h
         #ifndef __FOO_H__
         #define __FOO_H__
         class Foo
         {
              ...
         };
         文件Foo.cpp
         #include "Foo.h"
         要实现的具体内容
         O-C类格式
         文件Foo.h
         @interface Foo:NSObject
         {
              ...
         };
         @end
         文件Foo.m
         #mport "Foo.h"
         @implementation Foo
         要实现的具体内容
         @end
     2,类的关键字
         类的声明使用:@interface Foo:NSObject
         类的继承使用:进行继承
         类的结束使用:@end
         类的实现使用:@implementation Foo表示
         包含头文件使用:#import "Foo.h"
     3,为什么很多了是以NS开头的
         在iPhone/iPad开发中,很多类是以NS名字空间开头的。原因是这些类是来源于Cocoa基础类,而Cocoa基础类最初来源于NeXTStep。所以Cocoa很多类是以NS开头命名。iOS使用了Cocoa基础类。Mac OS X叫Cocoa,在iOS中叫Cocoa Touch。
     4,To import or include?
         #import head.h,Obj-C语言包含头文件格式。
         C/C++使用#inlcude来包含头文件。缺点就是可能同一个头文件可能被包含多次。
         Objective-C使用了#import来包含头文件。优点就是同一个头文件只能包含一次。
     5,C++属性方法
         文件Foo.h
         class Foo{
              double x;
         public:
              int f(int x);
              float g(int x, int y);
         };
         文件Foo.cpp
         #include "Foo.h"
         int Foo::f(int x){…}
         float Foo::g(int x, int y){…}
         O-C属性方法
         文件Foo.h
         @interface Foo:NSObject
         {
              double x;
         }
         -(int)f : (int)x;
         -(float)g : (int)x : (int)y;
         @end
         文件Foo.m
         #import "Foo.h"
         @implementation Foo
         -(int)f : (int)x{…}
         -(float)g : (int)x : (int)y{…}
         @end
     6,在O-C中属性的声明只能在@interface{和}直间。属性的使用和C语言类似。在@interface{和}之间不能定义方法。方法的定义是:-(int)f : (int)x。这里“-”表示对象的方法,“+”表示类的方法。返回值或者参数的类型声明是使用()包含。参数分割使用“:”来分开。
         例如:
         -(void)insertObject:(id)anObject atIndex:(NSUInteger)index;
         注解:“-”只能通过对象来调用这个函数。返回值类型为void。函数名为insertObject:和atIndex:,参数为id anObject,和NSUInteger index。冒号是函数名的一部分。在OC中不会出现函数名相同的函数,不能重载。形参的类型用括号括起来,后面是形参名。有几个形参就有几个冒号。
     7,多参数方法及调用
         -(int)f : (int)x;类似于C++中int f(int x);
         函数不带参数:-(int) f;调用:[对象名 f]或[self f]
         带一个参数:-(int)f:(int)x;调用:[对象名 f:10]或[self f:10]
         带两个参数:-(int)f:(int)x : (int)y。调用:[对象名 f:10:20]或[self f:10:20].
demo2
MyPoint.h
#import <Cocoa/Cocoa.h>
 
@interface MyPoint : NSObject
{
     int x;
     int y;
}
//-(void)initWithX:(int)m andY:(int)n;
-(id)initWithX:(int)m andY:(int)n;
-(void)showXAndY;
 
@end
 
MyPoint.m
#import "MyPoint.h"
 
@implementation MyPoint  
 
//-(void)initWithX:(int)m andY:(int)n
//{
//  x = m;
//  y = n;
//}
-(id)initWithX:(int)m andY:(int)n
{
     self = [super init];    //固定格式,模板。 self相当于C++中的this。[super init]表示对象会强制去调用父类的init。
     if (self) {//如果父类成功调用,则初始化子类,否则返回nil.
          x = m;
          y = n;
     }
     return self;
}
 
-(void)showXAndY
{
     NSLog(@"x = %d y = %d", x, y);
}
 
@end
 
main.m
int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
//  MyPoint * mp = [[MyPoint alloc] init];   通过类名去调用alloc,返回一个对象,这个对象再调用init函数进行初始化。
//  [mp initWithX:10 andY:20];
     MyPoint * mp = [[MyPoint alloc] initWithX:10 andY:20];
     [mp showXAndY];
    
     [mp release];  //释放。
    
    [pool drain];
    return 0;
}
练习:
demo3
Complex.h
#import <Cocoa/Cocoa.h>
 
@interface Complex:NSObject
{
     double _real;
     double _imaginary;
}
-(void)setReal:(double)a;
-(void)setImaginary:(double)b;
-(void)print;
-(double)real;
-(double)imaginary;
 
@end
 
Complex.m
#import "Complex.h"
 
@implementation Complex
 
-(void)setReal:(double)a
{
     _real = a;
}
 
-(void)setImaginary:(double)b
{
     _imaginary = b;
}
 
-(void)print
{
     NSLog(@"display as %.2lf + %.2lf", _real,_imaginary);
//  NSLog(@"display as %.2lf + %.2lf", [self real], [self imaginary]);
}
-(double)real
{
     return _real;
}
 
-(double)imaginary
{
     return _imaginary;
}
@end
 
main.m
#import <Foundation/Foundation.h>
#import "Complex.h"
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     Complex *cp = [[Complex alloc] init];
     [cp setReal:5];
     [cp setImaginary:6];
     [cp print];
     double retreal = [cp real];
     double retimaginary = [cp imaginary];
     NSLog(@"%.2lf %.2lf", retreal, retimaginary);
     [cp release];
    [pool drain];
     return 0;
}
 
demo4
Rectangle.h
#import <Cocoa/Cocoa.h>
 
@interface Rectangle : NSObject
{
     int _width;
     int _height;
}
 
-(void)setWidth:(int)w;
-(void)setHeight:(int)h;
-(int)width;
-(int)height;
-(int)area;
-(int)perimeter;
 
@end
 
Rectangle.m
#import "Rectangle.h"
 
@implementation Rectangle
 
-(void)setWidth:(int)w
{
     _width = w;
}
-(void)setHeight:(int)h
{
     _height = h;
}
-(int)width
{
     return _width;
}
-(int)height
{
     return _height;
}
-(int)area
{
     return _height * _width;
}
-(int)perimeter
{
     return 2 * (_height + _width);
}
 
@end
 
main.m
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     Rectangle * rt = [[Rectangle alloc] init];
#if 0
     [rt setWidth:3];
     [rt setHeight:4];
     NSLog(@"width:%d, height:%d", [rt width], [rt height]);
     NSLog(@"area:%d, perimeter:%d", [rt area], [rt perimeter]);
#else
     rt.width = 3;
     rt.height = 4;
     NSLog(@"width:%d, height:%d, area:%d, perimeter:%d", rt.width, rt.height, rt.area, rt.perimeter);
    
#endif
     [rt release];
     [pool drain];
     return 0;
}
 
demo5
MyStack.h
#import <Cocoa/Cocoa.h>
 
typedef int ele_t;
#define INITSIZE 5
#define INCREMENTSIZE 10
 
@interface MyStack:NSObject
{
     size_t size;
     size_t length;
     ele_t * top;
     ele_t * base;
}
-(void)resize_stack;
-(BOOL)isFull;
-(BOOL)isEmpty;
-(void)push_stack:(ele_t *)pe;
-(ele_t)pop_stack;
 
@end
 
MyStack.m
#import "MyStack.h"
 
@implementation MyStack
-(id)init
{
     self = [super init];
     if (self != nil) {
         //在这里面完成我们的自定义初始化。
         base = (ele_t *)malloc(sizeof(ele_t) * INITSIZE);
         if (NULL == base) {
              printf("malloc");
              exit(-1);
         }
         top = base;
         size = INITSIZE;
         length = 0;
     }
    
     return self;
}
-(void)dealloc
{
     printf("dealloc is called\n");
     free(base);
    
     [super dealloc];
}
-(void)resize_stack
{
     size += INCREMENTSIZE;
     base = (ele_t *)realloc(base, sizeof(ele_t) * size);
     if (NULL == base) {
         printf("realloc");
         exit(-1);
     }
     top = base + length;
}
 
-(BOOL)isFull
{
     return length == size;
}
 
-(BOOL)isEmpty
{
     return 0 == length;
}
 
-(void)push_stack:(ele_t *)pe
{
     if ([self isFull]) {
         [self resize_stack];
     }
     *top = *pe;
     top++;
     length++;
}
 
-(ele_t)pop_stack
{
     if ([self isEmpty]) {
         ele_t e;
         memset(&e, -1, sizeof(ele_t));
         return e;
     }
     top--;
     length--;
     return *top;
}
@end
 
main.m
#import <Foundation/Foundation.h>
#import "MyStack.h"
 
int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    MyStack * ms = [[MyStack alloc] init];
     for(int i = 1; i < 11; i++){
         [ms push_stack:&i];
         printf("%d\n", i);
     }
     printf("pop_stack\n");
    
     for(int i = 1; i < 11; i++)
     {
         printf("%d\n", [ms pop_stack]);
     }
    
     [ms release];
    [pool drain];
    
    return 0;
}
0 0
原创粉丝点击