以下是我写的一个实例, 测试Objective-c是如何使用类的
TestClass.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// // TestClass.h // TestClass // // Created by exchen on 6/15/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> @interface TestClass : NSObject{ //public成员变量 @public int number1; int number2; NSString *Nstr; char strArray[20]; } //成员函数声明 -(void)print; -(void)calc; -(NSString*)strAppend:(NSString*) string1:(NSString*) string2; @end |
TestClass.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// // TestClass.m // TestClass // // Created by exchen on 6/15/15. // Copyright (c) 2015 exchen. All rights reserved. // #import "TestClass.h" #import <stdio.h> @implementation TestClass //成员函数实现 -(void) print{ printf("%d\n",number1); NSLog(Nstr); printf("%s\n",strArray); } -(void) calc{ number1 += number2; printf("%d\n",number1); } -(NSString*)strAppend:(NSString*) string1:(NSString*) string2{ NSString *strRet = [string1 stringByAppendingString:string2]; return strRet; } @end |
main.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// // main.m // TestClass // // Created by exchen on 6/15/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> #import "TestClass.h" int main(int argc, const charchar * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); } TestClass *tc = [[TestClass alloc] init]; //分配内存 tc->number1 = 1; //给类成员变量赋值 tc->number2 = 2; [tc calc]; //调用类成员函数 strcpy(tc->strArray,"strArray"); //给类成员字符串变量赋值 [tc print]; //调用类成员函数 NSString *strRet = [tc strAppend:@"string1" :@"string2"]; //调用带参数的函数 NSLog(strRet); //打印返回值 return 0; } |
转载请注明:exchen's blog » Objective-c 创建类的使用