Object-C 类定义
该文章用于展现 Object-C中的类的基本结构,以便参考。
1、头文件定义:AlsTemplate.h
// // AlsTemplate.h // EasyObjectC // // Created by Allison on 13-9-20. // Copyright (c) 2013年 RuiHuang. All rights reserved. // #import <Foundation/Foundation.h> @interface AlsTemplate : NSObject { NSString *strMember; } @property (nonatomic, retain) NSString *strMember; - (id) init; - (id) initWithValue: (NSString *)initValue; - (void) someMethod: (NSString *) firstParam secondParam: (int) secondParam; + (id) fooWithValue: (NSString *) initValue; @end
2、事项文件定义:AlsTemplate.m
// // AlsTemplate.m // EasyObjectC // // Created by Allison on 13-9-20. // Copyright (c) 2013年 RuiHuang. All rights reserved. // #import "AlsTemplate.h" @implementation AlsTemplate @synthesize strMember; // 结构体 typedef struct { float x; float y; } PointStruct; // 枚举 enum MyEnumType { VALUE1, VALUE2, VALUE3 }; typedef enum MyEnumType MyEnum; #pragma mark - system method - (void) close { // add release code [strMember release]; strMember = nil; } - (void) dealloc { [self close]; [super dealloc]; } //- (void) finalize { // [self close]; // [super finalize]; //} - (id) init { if (self = [super init]) { // add init code strMember = [[NSString alloc] init]; } return self; } - (id) initWithValue:(NSString *)initValue { if (self = [self init]) { // add your init code strMember = [initValue retain]; NSLog(@"strMember=%@", strMember); } return self; } // 静态方法 + (id) fooWithValue:(NSString *)initValue { return [[[self alloc]initWithValue:initValue] autorelease]; } #pragma mark - my method - (void) someMethod:(NSString *)firstParam secondParam:(int)secondParam { NSLog(@"someMethod, strMember=%@, firstParap=%@, secondParam=%d", strMember, firstParam, secondParam); PointStruct p; p.x = 10; p.y = 20; NSLog(@"The struct test x=%f, y=%f", p.x, p.y); // 枚举初始化 MyEnum myEnum = VALUE3; NSLog(@"The enum test, value3=%d", myEnum); } @end
3、使用方法:main.m
// // main.m // EasyObjectC // // Created by Allison on 13-9-18. // Copyright (c) 2013年 RuiHuang. All rights reserved. // #import <Foundation/Foundation.h> #import "AlsTemplate.h" #import "TestClass.h" int main(int argc, const char * argv[]) { @autoreleasepool { // Test my code AlsTemplate *myTemplate = [[AlsTemplate alloc] init]; [myTemplate someMethod:@"FirstValue" secondParam:100]; [myTemplate release]; [AlsTemplate fooWithValue:@"method of class test."]; } return 0; }
版版权所有:ForrestWang,转载请注明出处!