OC 詳解(持續更新)

架構

OC 使用例子:

Objective-C 入門教程

#import <Foundation/Foundation.h>

@interface A : NSObject
-(void)dealloc;
-(id)init;
@end

@interface B: NSObject {
A* mya;
}
-(void)dealloc;
-(id)init: (A*) a;
+(void)print;
@end

@implementation A

-(void)dealloc
{
NSLog(@"A dealloc");
}
-(id) init {
NSLog(@"A init");
return self;
}
@end

@implementation B
-(id)init: (A*) a {
mya = a;
return self;
}
+(void)print {
NSLog(@"B print");
}

@end

B *b = NULL;
void foo2(A *a) {
NSLog(@"A foo2");
//B *b = [[B alloc] init: a];
}

void foo3(NSString * str){

}

void foo1 () {
NSLog(@"A foo1");
A * a = [[A alloc] init];
foo2(a);
NSLog(@"foo1 over");
}

int main(int argc, const char * argv[]) {
@autoreleasepool {
__block int b =5; // __block將棧改為堆
void(^myBlock)()=^{
NSLog(@"Hello, World!");
b = 20; // 會修改外部b
};
myBlock();
NSLog(@"Hello, World!,%d", b);
}
foo1();
[B print];
NSLog(@"over");

return 0;
}

// example 2:

#import<Foundation/NSObject.h>
@interface A:NSObject {
int a =1;
int b =2;
}
-(int)add: (int) c AB: (int)d;
@end

@implementation A

-(int)add: (int) c AB: (int)d {
return a+b+c+d;
}

@end

赞(0)