Objective-C 知識點總結


一、objective-c 基礎

OC是C語言的超集,是在C語言的基礎上添加了面向對象的特性。


1. 與C語言相同的部分

基本數據類型,數組,流程控制,指針,結構體,枚舉,函數指針


2. 方法聲明與調用

方法聲明與C語言有很大差別,oc中的方法都是在類中聲明的,用 - 表示實例方法,用 + 表示類方法,

返回值用 (typename)表示,方法名和參數用 : 分隔,而且 : 是方法名的一部分(部分方法名),不同參數用空格分隔,

(Methods and properties for the class are declared next, before the end of the class declaration. The names of

methods that can be used by class objects, class methods, are preceded by a plus sign)

+(instancetype) alloc;

(The methods that instances of a class can use, instance methods, are marked with a minus sign)

如:

-(void)removeObjectAtIndex: (NSInteger)index withFlag:(BOOL)flag;

調用時用 [instance method],稱為:向instance發送 method 消息。

注意:Class methods can’t refer directly to instance variables.

3. 面向對象的語法支持

(Class Interface):用interface聲明一個類,實例化后的對象都是指針

The declaration of a class interface begins with the compiler directive @interface and ends with 

the directive  @end. (All Objective-C directives to the compiler begin with“@”.)

            聲明:在 .h 文件中,

                  @interface ClassName : SuperClass

                  @end

            實現(Class Implementation)在 .m 文件中

The definition of a class is structured very much like its declaration. It begins with an @implementation

directive and ends with the @end directive. In addition, the class may declare instance variables in braces after

the @implementation directive:

                  @implement ClassName

                  @end

協議(protocol):相當於Java的接口,只定義方法, 遵守此協議的類需要實現這些方法

            聲明:

                  @protocol ProtocolName

                  @end

            遵守協議: @interface ClassName : SuperClass <ProtocolName1, ProtocolName2>

optional 的方法是可選的,遵守協議時可以不用實現這些方法;required 的方法是必須要實現的,默認是 required 的

繼承(Inheritance):定義類的時候可以用 :來表示繼承關系,oc只能單繼承,一般定義一個類都要但是一個類可以實現多個協議,可以通過這種方式來實現多繼承。

多態(polymorphism):動態綁定;不同的對象能夠以自己的方式響應相同消息的能力;子類可以重寫父類的方法。

The ability of different objects to respond, each in its own way, to identical messages is called polymorphism .

隱藏變量(self, super, _cmd):實例對象可以用 self 表示自己,super 可以調用父類方法。類方法中的 self 表示類本身。每一個方法內都有一個_cmd,表示方法自身,它是 SEL 類型,可以使用 NSStringFromSelector 方法得到 _cmd 的字符串表達。

注意:Within the body of a class method, self refers to the class object itself. 類方法中 self 代表類本身。

類別(category):類別用來給一個類添加新方法,不可以給類添加成員變量。在聲明類的時候,在類名后面添加一對括號,其中指定類別的名字。

(1)類別只能添加新方法,無法添加新的實例變量

(2)如果類別名和原來類中的方法產生名稱沖突,則類別將覆蓋原來的方法,因為類別具有更高的優先級。

擴展(Extension):與類別相似,但是也有一些差別。

類的擴展和類別一樣,在類名后添加一對括號,但擴展不需要名字。類的擴展中,可以添加實例變量。

通常,把類的私有變量和私有方法放在擴展中,以此來隱藏信息。

類的擴展必須放在該類的實現文件中,並且要實現擴展中聲明的方法。而類別是可以放在一個單獨的文件中聲明和實現的。

作用域(Scope):To enforce the ability of an object to hide its data, the compiler limits the scope of instance variables—that is,

limits their visibility within the program. But to provide flexibility, it also lets you explicitly set the scope at four

levels. Each level is marked by a compiler directive:



5. 方法選擇器

用 SEL 可以聲明一個方法: SEL sel = @selector(methodName), 可以當做參數傳遞給一個方法

[myRectangle setOriginX: 30.0 y: 50.0];

A selector name includes all the parts of the name, including the colons, so the selector in the preceding

example is named setOriginX:y:. It has two colons, because it takes two parameters. The selector name

does not, however, include anything else, such as return type or parameter types.

eg:

SEL setWidthHeight;

setWidthHeight = @selector(setWidth:height:);

setWidthHeight = NSSelectorFromString(aBuffer);


5. 屬性與屬性修飾詞

類可以有若干個屬性,用@property 來聲明,如:@property ( nonatomic, assign)NSInteger score;

這樣該類就有一個私有變量 _score,並且自動生成了 getter 和 setter。

可以給屬性指定若干個修飾詞,用逗號隔開。

如: notatomic, copy, weak, strong, assign, unsage_unretained, readwrite, readonly,setter=name,getter=name 等等。

注意:沒有與 nonatomic 對應的 atomic,沒有 指定 nonatomic 的默認都是 atomic


6. id 和 instancetype 類型

typedef struct objc_object {

    Class isa;

} *id;


7. 導入頭文件(Importing the Interface)

OC中用 #import "header.h" 導入類的頭文件,類似於C語言中的 #include。

#import 能夠防止重復導入。

除了直接import其他類的頭文件來引用該類,還可以用 @class  className 來告訴編譯器這是一個類。

@class Rectangle, Circle;

This directive simply informs the compiler that “Rectangle” and “Circle” are class names. It doesn’t import their interface files.


8. 塊(block)

block類似函數指針,就是定義了一個代碼塊。

void (^blockName)(int, int) = ^(int, int){

}

block代碼塊中可以訪問block之外的變量,但是不能修改,如果聲明變量時添加 __block ,則可以在block中修改變量。


9. 類型編碼(Type Encodings)

可以使用 @encode() 這個編譯指令來過去一個基本類型的字符串表達式。

To assist the runtime system, the compiler encodes the return and argument types for each method in a character string and associates the string with the method selector. The coding scheme it uses is also useful in other contexts and so is made publicly available with the @encode() compiler directive. When given a type specification, @encode() returns a string encoding that type. The type can be a basic type such as an int, a pointer, a tagged structure or union, or a class name—any type, in fact, that can be used as an argument to the C sizeof() operator.

   

   

    

  


10. 鍵值編碼(Key-value coding)

Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify

properties, rather than through invocation of an accessor method or accessing them directly through instance

variables. In essence, key-value coding defines the patterns and method signatures that your application’s

accessor methods implement.


NSKeyValueCoding 類中對 NSSet, NSOrderedSet, NSMutableDictionary, NSDictionary, NSArray,  NSObject 用類別添加了

鍵值編碼的方法。

A key is a string that identifies a specific property of an object. Typically, a key corresponds to the name of an

accessor method or instance variable in the receiving object. Keys must use ASCII encoding, begin with a

lowercase letter, and may not contain whitespace.


A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse.

The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated

relative to the value of the previous property.


如果 valueForKey:  指定的 key 不存在,那么默認會引發一個 NSUndefinedKeyException 的異常;子類也可以重寫

 valueForUndefinedKey: 方法來修改默認的行為。


鍵值編碼一致性的要求:


Accessor Search Implementation Details


Collection Operators

Collection operators allow actions to be performed on the items of a collection using key path notation and

an action operator. This article describes the available collection operators, example key paths, and the results

they’d produce.

Collection operators are specialized key paths that are passed as the parameter to the valueForKeyPath:

method. The operator is specified by a string preceded by an at sign (@). The key path on the left side of the

collection operator, if present, determines the array or set, relative to the receiver, that is used in the operation.

The key path on the right side of the operator specifies the property of the collection that the operator uses.


11. 鍵值監聽(Key-Value Observing)

Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of

other objects.It is particularly useful for communication between model and controller layers in an application.

There are three steps to setting up an observer of a property. Understanding these three steps provides a clear

illustration of how KVO works.


-(void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

向一個對象發送此消息,那么就會給該對象添加一個監聽者observer,同時,observer 中要實現:

-(void)observerValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;

這樣,被監聽的對象的屬性發生改變時就會調用這個方法,來通知 observer。


12. 單例

In a more sophisticated implementation, you can declare a variable to be static, and provide class methods

to manage it. Declaring a variable static limits its scope to just the class—and to just the part of the class

that’s implemented in the file. (Thus unlike instance variables, static variables cannot be inherited by, or directly

manipulated by, subclasses.) This pattern is commonly used to define shared instances of a class (such as

singletons; see “Creating a Singleton Instance” in Cocoa Fundamentals Guide ).

static MyClass *MCLSSharedInstance;

@implementation MyClass

    + (MyClass *)sharedInstance

    {

        // check for existence of shared instance

        // create if necessary

        return MCLSSharedInstance;

    }

// implementation continues


13. 不顯示警告


   未使用的警告:__unused

   方法deprecated的警告:

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wdeprecated-declarations”

#pragma clang diagnostic pop



二、Apple提供的框架


1. Foundation


2. UIKit


3. CoreGraphics


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: