以下是我寫的一個實例, 測試Objective-c是如何使用類的
TestClass.h
// // TestClass.h // TestClass // // Created by exchen on 6/15/15. // Copyright (c) 2015 exchen. All rights reserved. // #import@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@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
// // main.m // TestClass // // Created by exchen on 6/15/15. // Copyright (c) 2015 exchen. All rights reserved. // #import#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; }
工程下載地址