Re: [問題] Xcode程式 Memory Manage的問題

看板MacDev作者 (狗狗)時間14年前 (2011/04/12 01:35), 編輯推噓2(203)
留言5則, 3人參與, 最新討論串3/3 (看更多)
※ 引述《jangin (我)》之銘言: : 各位前輩們,請問一個問題 : 在MyViewController.h檔中 : @interface MyViewController:UIViewController { : IBOutlet UITextField *pageinfo_display; : } : @end 你沒有設定@property嗎?建議把pageinfo_display設為property(retain) : 在MyViewController.m中 : @interface MyViewController() : int currentPage; : int totalPage; : @end 我很好奇的是 在anonymous category (Class Extension)裡面可以宣告變數嗎? : @implement MyViewController : -(void) updatePageInfo : { : pageinfo_display.text = [[NSString alloc] initWithFormat: : @"%d / %d",currentPage,totalPage]; : } : @end : 我的問題是 : (1) pageinfo_display.text = ... : (這樣子setter 是不是會自動先做Release 再做新的NSString指定) : 記得在斯坦福的線上影片曾看到 setter 會是 先做Release 再assign. : 不知道自己有沒有會錯意,影片是英文的@@ UITextField的text的property設定為retain 因此使用此setter會導致retain count +1 而你alloc該NSString,所以你有「責任」去release它! : (2) 還是在等於的後面的NSString alloc 加上autoRelease : [[[NSString alloc] initWithFormat: : @"%d / %d",currentPage,totalPage]autorelease]; 這樣寫法是OK的 但是等於NSString本身就有提供的convenient class method +(id) stringWithFormat: : (3) 1和2 都不對,請各位前輩幫忙解說一下,非常感謝。 memory management的原則很簡單... 「誰製造問題,誰就有責任去解決」 所以當你alloc/copy/retain一個物件時,就有「責任」必須在適當的位置去release它 像setter本身有retain物件的話,它就會在下次set別的物件時將舊有的物件release掉 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.80.144.89 ※ 編輯: leondemon 來自: 111.80.144.89 (04/12 01:37)

04/12 12:51, , 1F
感謝解答,在.m中宣告變數,是從斯坦福第二堂課抄來的
04/12 12:51, 1F

04/12 15:49, , 2F
anonymous category裡面不能宣告變數 至少我compile不過
04/12 15:49, 2F

04/12 19:26, , 3F
新手請多多指教,上面的寫法,我可以compile and執行
04/12 19:26, 3F

04/12 21:59, , 4F
那樣的設法,八成是global variable吧…
04/12 21:59, 4F

04/12 22:00, , 5F
category除了anonymous可以設properties之外,其它的不行。
04/12 22:00, 5F
文章代碼(AID): #1Depls2b (MacDev)
文章代碼(AID): #1Depls2b (MacDev)