iOS開發(fā)中使用的語言是objective C.它是一種面向?qū)ο蟮恼Z言,因此有面向?qū)ο笳Z言編程的一些背景會很容易理解。
在Objective-C類的聲明文件被稱為接口文件和文件定義類被稱為實現(xiàn)文件。
類似于下面的一個簡單的接口文件MyClass.h
@interace MyClass:NSObject{ // class variable declared here } // class properties declared here // class methods and instance methods declared here @end
實現(xiàn)文件 MyClass.m 如下
@implementation MyClass // class methods defined here @end
對象的創(chuàng)建完成如下
MyClass *objectName = [[MyClass alloc]init] ;
Objective-C的方法中聲明如下
-(returnType)methodName:(typeName) variable1 :(typeName)variable2;
一個例子如下所示
-(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth;
可能想知道什么是andBreadth字符串,實際上這有助于我們閱讀和理解方法,特別是在調(diào)用的時候,其可選的字符串。要在同一類中調(diào)用此方法,我們使用下面的語句
[self calculateAreaForRectangleWithLength:30 andBreadth:20];
正如上面所說的使用andBreadth有助于我們理解,breath 是20。self 用于指定它是一個類方法。
類方法可以直接訪問,而無需創(chuàng)建類的對象。他們沒有任何與它相關(guān)聯(lián)的變量和對象。例子如下所示。
+(void)simpleClassMethod;
它可以訪問使用類名(我們假設(shè)MyClass作為類名)如下。
[MyClass simpleClassMethod];
實例方法可以訪問后,才創(chuàng)建的類的對象。實例變量分配內(nèi)存。的一個例子的實例方法如下所示。
-(void)simpleInstanceMethod;
它可以訪問如下的類創(chuàng)建對象后,
MyClass *objectName = [[MyClass alloc]init] ; [objectName simpleInstanceMethod];
S.N. | 數(shù)據(jù)類型 |
---|---|
1 |
NSString It is used for representing a string |
2 |
CGfloat It is used for representing a floating yiibai value (normal float is also allowed but it's better to use CGfloat) |
3 |
NSInteger It is used for representing integer |
4 |
BOOL used for representing Boolean(YES or NO are BOOL types allowed ) |
NSLog - 使用打印一份聲明。這將是打印的設(shè)備的日志和調(diào)試控制臺釋放和調(diào)試模式。
Eg: NSlog(@"");
大多數(shù)的控制結(jié)構(gòu)中的相同,C和C ++除了在聲明中添加了一些像。
使用一個外部類訪問類變量屬性
Eg: @property(nonatomic , strong) NSString *myString;
可以使用點運算符來訪問屬性。訪問上述物業(yè),我們將做到以下幾點。
self.myString = @"Test";
也可以使用設(shè)置方法如下。
[self setMyString:@"Test"];
類別將方法添加到現(xiàn)有的類。通過這種方式,我們可以添加類的方法,而我們甚至沒有實施實際的類定義文件。我們的類是一個樣本類別如下。
@interace MyClass(customAdditions) - (void)sampleCategoryMethod; @end @implementation MyClass(categoryAdditions) -(void)sampleCategoryMethod{ NSLog(@"Just a test category"); }
NSMutableArray和NSArray是Objective-C中的數(shù)組類。顧名思義,前者是可變的,后者是不可改變的。一個例子如下所示:
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init]; [anArray addObject:@"firstobject"]; NSArray *aImmutableArray = [[NSArray alloc] initWithObjects:@"firstObject",nil];
NSMutableDictionary和NSDictionary是字典使用Objective-C類。顧名思義,前者是可變的,后者是不可改變的。例子如下所示:
NSMutableDictionary*aMutableDictionary = [[NSMutableArray alloc]init]; [aMutableDictionary setObject:@"firstobject" forKey:@"aKey"]; NSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects: @"firstObject",nil] forKeys:[ NSArray arrayWithObjects:@"aKey"]];