2013年9月19日 星期四

筆記,iOS中的alloc 與init V.S. new


關於iOS中的alloc和init這兩個方法一直覺得很疑惑,難道沒有一個和JAVA一樣的new XXX()方法可以使用嗎?看過去前輩們寫的app幾乎都還是乖乖的用[xxx alloc]然後[xxx init]或是[xxx initWith..]之類的方法,好奇查了一下相關的解答:

連結在這裡

問題:

I am little bit confuse about new and [[alloc]init]. I think this is small question. I have defined content object using new and [[alloc]init].
(1). NSMutableArray *content =[NSMutableArray new];
(2). NSMutableArray *content = [[NSMutableArray alloc] init];
What my question is difference between new and [[alloc]init]. I only know above (1) and (2) are similar. If (1) and (2) are similar then why do we use [[alloc]init] compare than new in most of time? I think they have small difference. Please explain any one to me.

最佳解答:
Alloc : Class method of NSObject. Returns a new instance of the receiving class.
Init : Instance method of NSObject. Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
New : Class method of NSObject. Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.
Release : Instance method of NSObject delegate. Decrements the receiver’s reference count.
Autorelease : Instance method of NSObject delegate. Adds the receiver to the current autorelease pool.
Retain: Instance method of NSObject delegate. Increments the receiver’s reference count.
Copy : Instance method of NSObject delegate. Returns a new instance that’s a copy of the receiver.
So to conclude we can say that
alloc goes with init
new = alloc + init

所以我的疑惑算是解決了。

沒有留言:

張貼留言

你好,我是小書,如果文章內容有錯誤,或是看到有建議以及任何感想時,歡迎提出分享,我們一起學習一起努力。

追蹤者