2015-04-05 24 views
-1
1) 
SKSpriteNode *node = [[SKSpriteNode alloc] initWithImageNamed:image]; 

2) 
node = [SKSpriteNode spriteNodeWithImageNamed:@"image"]; 

我見過使用兩種方式的代碼示例,我不確定什麼是最好的,爲什麼。在1)情況下,究竟「alloc」代表什麼?有人ELI5這兩行代碼的區別?

回答

1

第一個聲明的變量node,並使用一個名爲image變量:

SKSpriteNode *node = [[SKSpriteNode alloc] initWithImageNamed:image]; 
^^^^^^^^^^^^^^            ^^^^^ 

第二個假設變量node已經存在,並使用字符串文字:

node = [SKSpriteNode spriteNodeWithImageNamed:@"image"]; 
               ^^^^^^^^ 

假設你正在使用自動參考計數或「ARC」(您幾乎可以肯定是),之間沒有顯着差異使用[[SKSpriteNode alloc] initWithImageNamed:...]和使用[SKSpriteNode spriteNodeWithImageNamed:]

如果您已經停用ARC在你的項目,或爲這個源文件,然後不同的是,alloc/init...返回+1引用,你必須releaseautorelease在某些時候,而spriteNodeWithImageNamed:返回一個自動釋放的引用,你必須retain如果你想保持它。如果您想了解更多關於Cocoa手動內存管理的細節,請先閱讀Cocoa Core Competencies: Memory management