《Programming with Objective-C》第三章 Working with Objects

Object和普通變量的區別

If you’re used to using terms like the stack and the heap, a local variable is allocated on the stack, while objects are allocated on the heap.ide

- (void)f
{
    int a = 2;                    //Stack
    NSString *s = @"Hello";        //Heap
}

函數f中,a指向的內存在棧中,函數退出的時候變量a將不能再被訪問,其內存也會被釋放;s指向的內存在堆中,函數退出的時候s也不能再被訪問,可是s指向的內存可能繼續存在。函數

 

Factory Method v.s. Abstract Factory

 Todo 等查找資料後再補上spa

 

Objective-C是一門動態語言

id someObject = @"Hello, World!";
[someObject removeAllObjects];

編譯時,someObject是一個id類型,因此編譯器不會報錯。
運行時,編譯器會出現Runtime Error由於NSString對象不能響應removeAllObjects.code

NSString *someObject = @"Hello, World!";
[someObject removeAllObjects];

編譯時,編譯器知道someObject是一個NSString類型,NSString對象不能響應removeAllObjects,因此編譯時編譯器會報錯對象

 

等於/不等於

//基本類型
if (someInteger == 42) 
{
    // someInteger has the value 42
}

//比較是不是同一個對象
if (firstPerson == secondPerson)    
{
    // firstPerson is the same object as secondPerson
}

//比較2個對象的內容是否相等
if ([firstPerson isEqual:secondPerson])     
{
    // firstPerson is identical to secondPerson
}

//NSNumber, NSString and NSDate等類型比較大小不能用>、<,應該用compare:方法
if ([someDate compare:anotherDate] == NSOrderedAscending) 
{
    // someDate is earlier than anotherDate
}
相關文章
相關標籤/搜索