標籤:
以下是我寫的一個執行個體, 測試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;}@end
main.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;}
工程
Objective-c 建立類的使用