源码:
#import <objc/objc.h> #import <objc/Object.h> //Test for method parameter @interface TestObj : Object { int num; } // no parameter - (void)foo; // 1 parameter - (void) test1: (int) n; // 2 parameter - (void) test2: (int) m param2: (int) n; // 3 parameter - (void) test3: (int) x param2: (int) y param3: (int) z; // 3 parameter without param name - (void) test4: (int) x : (int) y :(int) z; @end @implementation TestObj - (void)foo { printf("foo\n"); } // 1 parameter - (void) test1: (int) n{ printf("test1 begin\n"); printf("1 parameter:%d\n",n); printf("test1 end\n"); } // 2 parameter - (void) test2: (int) m param2: (int) n{ printf("test2 begin\n"); printf("1 parameter:%d\n",m); printf("2 parameter:%d\n",n); printf("test2 end\n"); } // 3 parameter - (void) test3: (int) x param2: (int) y param3: (int) z{ printf("test3 begin\n"); printf("1 parameter:%d\n",x); printf("2 parameter:%d\n",y); printf("3 parameter:%d\n",z); printf("test3 end\n"); } // 3 parameter without param name - (void) test4: (int) x : (int) y : (int) z{ printf("test4 begin\n"); printf("1 parameter:%d\n",x); printf("2 parameter:%d\n",y); printf("3 parameter:%d\n",z); printf("test4 end\n"); } int main() { id obj = [[TestObj alloc] init]; [obj foo]; [obj test1:1]; [obj test2:2 param2:3]; [obj test3:4 param2:5 param3:6]; [obj test4:7 :8 :9]; return 0; } @end
说明:
1.类的基本语法,包括interface声明和implementation实现
@interface TestObj : Object
@end
@implementation TestObj
@end: Object 是指继承自Object
2.类的数据成员
{ int num; }
3.方法声明
// test3是方法名, (int) x前省略实参名 param1, param2/3是实参名,x y z是实参的变量名 - (void) test3: (int) x param2: (int) y param3: (int) z; // 实参名可以省略 - (void) test4: (int) x : (int) y :(int) z;如果没有参数的话,方法名testx后面不需要跟冒号:
方法开头有减号或者加号-/+,类似java中的普通方法和静态方法,决定是否可以直接调用还是需要类的实例才能调用
4. 对象初始化
id obj = [[TestObj alloc] init];4.1 等号左边有两种方式
id obj =
TestObj *obj =
id是一个虚拟的对象声明指针,所以obj前面不需要*号
4.2类的初始化可以使用alloc init或者new:
className* object = [className new];
className* object = [[className alloc] init];
背景说明,new是较为老式的写法,后来发现只有一个new不好使,才引入了alloc和init这种写法,保留new一是向后兼容,二是很多时候是一种更简单的写法。其实是一样的,new在内部调用的alloc和init.
源代码:
+ new { id newObject = (*_alloc)((Class)self, 0); Class metaClass = self->isa; if (class_getVersion(metaClass) > 1) return [newObject init]; else return newObject; }
+ alloc { return (*_zoneAlloc)((Class)self, 0, malloc_default_zone()); }
- init { return self; }
[className new]基本等同于[[className alloc] init]. 区别只在于alloc分配内存的时候使用了zone,这个zone是个什么东东呢?它是给对象分配内存的时候,把关联的对象分配到一个相邻的内存区域内,以便于调用时消耗很少的代价,提升了程序处理速度.
什么要把alloc 和init 分开?
1. 可以使用多种init方法
2. 显示调用总比隐式调用要好”
如果确实不需要用其他的init函数,比如initWithString, 只是使用 [Nsobject alloc] init] ,那用new的方法更加方便
* new doesn't support custom initializers (like initWithString)
* alloc-init is more explicit than new