以下是我写的一个实例, 测试Objective-c是如何使用类的
TestClass.h
// // 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
// // 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; } @endmain.m
// // 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 char * 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; }
原文:http://blog.csdn.net/sysprogram/article/details/46507323