これ。はまりました。
画面上に今日の日付を表示したい。
画面を表示する度に日付を取得し直すのもあれなので、
一度画面をロードしたタイミングで日付を取得して
それを変数で保持しておこうと。
というわけでこんなコードを書いてました。
コントローラのヘッダファイルで以下のプロパティを指定
@property (nonatomic, retain) NSDate *targetDate; |
実装ファイル中のviewDidLoadでこんな感じで
今日の日付をセットしてました。
- (void)viewDidLoad {
targetDate = [NSDate date];
} |
すると初回の表示では正しく日付が取得できていたのですが、
2回目以降だとエラーで落ちてしまう。
デバッグしてみるとセットしたはずの日付がなくなっているではないか。
おかしい。。。
試しにこんなコードにしてみる。
- (void)viewDidLoad {
targetDate = [[NSDate date] retain];
} |
おっ。エラーが出なくなった。と。
いろいろ調べてみると
[NSDate date]がautoreleaseされるインスタンスを
返していることが原因でした。
これにはobjective-cのメモリ管理方法の理解が必要なのでまとめます。
retainとrelease
objective-cでは参照カウンタ方式というメモリ管理を行っています。インスタンスの参照が増えるとカウンタが1、2、3、、、
と増えていき、参照が減るとカウンタ3、2、1、、、
と減り、参照カウンタが0になるとdeallocメソッドが呼ばれます。
参照が減るのは[obj release]のようにreleaseが呼ばれた時と、
[[[NSDate] init] ]autorelease]のようなautoreleaseされる
インスタンスが自動でreleaseされた時。
autoreleaseされるインスタンスは基本的に参照を一時的に持つもので
[[[NSDate] init] ]autorelease];
のように作られたインスタンスは勝手にreleaseされます。
メソッド内でのみ参照する場合などに使えます。
参照が増えるのは[NSDate date]などのようにインスタンスが
生成された場合と、[obj retain]のようにretainが呼ばれた時。
問題はobjective-cではautorelease用とautoreleaseされない
インスタンスを返す2種類の初期化メソッドがあることです。
初期化の方法
今回のNSDateで言うと[NSDate date]
これは、autoreleaseされるインスタンスを返します。
なのでメソッドが終わると参照カウンタが1減ります。
[[NSDate alloc] init](allocでインスタンスを生成。initで初期化)
これは、autoreleaseされないインスタンスを返します。
なのでメソッドが終わっても参照カウンタは減りません。
objective-cのメソッド名でinitから始まるものはautorelease
されないものらしいです。
逆にクラス名からはじまるもの。例えば
[NSDate date]
[NSString stringWIthFormat:@"%d"]
などはautoreleaseされるもののようです。
なので[NSDate date] と [[[NSDate alloc] init ] autorelase]は同義。
ということなので、autoreleaseされて参照カウンタが減ってしまうのなら
retainを使って増やしてやればカウンタ数に変化はないので
targetDate = [[NSDate date] retain]; |
とすればエラーが起きない。という現象でした。
でもautorelease→retainするくらいなら
はじめからinitすればいいじゃん。ってわけで
targetDate = [[NSDate alloc] init]; |
これでも問題なく動きます。
getter/setter
今回の件はgetter/setterの使われ方も絡んでいます。今回は以下のようなコードでした。
targetDate = [NSDate date]; |
これは変数targetDateにsetterを介さず
直接インスタンスをセットしています。
でもこんなコードの場合、setterが呼ばれます。
self.targetDate = [NSDate date]; |
setterを読んだ場合、このコードでエラーが起きなくなります。
それはsetter内で渡されたインスタンスをretainしているからです。
冒頭で書いたようにプロパティは以下のような定義をしていました。
@property (nonatomic, retain) NSDate *targetDate; |
このプロパティのretain指定によって、setterが呼ばれると
渡されたインスタンスをretainしてから、変数にセットする処理が
走るようになります。
よくサンプルコードなどで
Sample *tmpSample = [[Sample alloc] init]; self.sample = tmpSample; [tmpSample release]; |
などのように変数をセットした後にreleaseしているのは、
setter内でretainされて参照カウンタが増えたので、
releaseで減らしてやっている。ということだったんですね。
インスタンスの参照カウンタの値は
[obj retainCount]
として取得できるので、
この値を追いかけると分かりやすいです。
ちなみにプロパティでretainを指定しなかった場合は
assignと見なされます。
assignのsetterの場合は、値をretainせずにただ代入するだけです。
基本的にインスタンスの管理は生成したクラス内でreleaseをする、
というお約束があるらしいので、setterは変数がオブジェクトの場合
retainをつけてdealloc時にreleaseするという感じでよいと思います。
セットしたインスタンスは即releaseという感じで。
まとめ
という訳で、今回のNSDate問題はtargetDate = [[NSDate alloc] init]; |
や
targetDate = [[NSDate date] retain]; |
や
self.targetDate = [NSDate date]; |
などで回避できる。ということでした。
javaやC#がmainだった僕にとっては
セットしたオブジェクトをなぜすぐにreleaseして
動くのかがよく分からなかったのですが
だいぶスッキリしました。
しかしガベージコレクションのありがたみが
分かってきた28の冬。
でもGC使うよりこっちの方が参照探しまわるGC分の
コストがかからないのでパフォーマンスは上がるはず。
ザ・ワールドも発動しないしね。
関連のあるアプリ
タグ: iPachi, iphone, NSDate, NSString, objecti, objective-c, アプリ, デバッグ, パチスロ, リリース, 収支
関連する投稿
22 Responses to “【objective-c】[NSDate date]でセットした変数が参照できずエラー”
コメント
Additional comments powered by BackType


2月 1st, 2009 at 4:41 PM
ちょうどこの問題に自分も当たっていたので、
すごくよく理解できました・・!
どうもありがとうございました。
2月 2nd, 2009 at 1:01 AM
>kさん
おぉ。お役に立てて光栄です。
ハマりどころはどんどん共有してきたいですね。
2月 3rd, 2009 at 10:49 AM
[...] りの時間を費やしてしまいました。 詳しくは、 http://iphone.longearth.net/2009/01/22/【objective-c】nsdate-dateでセットした変数が参照できずエラー http://www.tech-arts.co.jp/macosx/macosx-jp/htdocs/4600/4620.html [...]
2月 8th, 2009 at 1:13 AM
非常有用哟!
努力吧!
谢谢!
2月 9th, 2009 at 7:37 AM
お役に立てて幸いです。
4月 1st, 2009 at 8:43 PM
technica place long reviews less 2000
4月 1st, 2009 at 8:43 PM
cycles list alternative routes majority 20th
4月 1st, 2009 at 8:43 PM
include attributed larger emitted open
4月 1st, 2009 at 8:43 PM
affected data panel medium
4月 1st, 2009 at 8:43 PM
species others iii resulted early volcanic server stratosphere
12月 15th, 2009 at 10:49 PM
6 adipex and sudafed or phentermine rx online order or what is tramadol with codeine or
8月 17th, 2010 at 5:14 AM
6 xanax street drug or 900mg tramadol per day or semen turns yellow viagra or
8月 17th, 2010 at 5:37 AM
6 8 cheap tramadol buy online or generic cialis mexico or purchase adipex no prescription or phentermine problem odor or cialis overnigth or prescritpion free phentermine or cialis identification or tylenol 3 and valium or adipex without prescriptiion or opioid methadone xanax or phentermine a173 or viagra male fertility research or adipex retard capsules or viagra users or adipex 37.5 buy online without prescription or are tramadol abused or heroin xanax bars or tramadol ups next day air or buy prescriptions online adipex or tramadol apap37 5mg 325mg or which is stronger valium or xanax or where to buy phentermine phoenix arizona or xanax dopamine or phentermine show up on drug tests or online pharmacist for phentermine or xanax and other simiar medication or blue cross blue shield cialis or phentermine side effects forum or order tramadol using cod or tramadol 3d or tramadol cash on delivery saturday delivery or phentermine creates erection or generic name for adipex or ultram patient information instructions tramadol hcl or lexapro taken with xanax and codeine or tramadol itchy skin or no prescription xanax online cheap xanax or 50 hcl mg tramadol or viagra on internet or phentermine causing headaches or viagra au or fast reliable phentermine without rx or adipex without dr prescription or difference between vicodin and valium or did you lose weight with adipex or extrapyramidal symptoms with valium or buy tramadol i want to or cialis and hip pain or phentermine no consultation internet pharmacy or frogdot viagra ad or
8月 17th, 2010 at 5:55 AM
7 tramadol or codeine or cialis generic price or revues sp cialis es en informatique or
8月 17th, 2010 at 6:03 AM
donde comprar cialis y levitra tabmd.com donde comprar viagra en chile medicamentos para el dolor su ,nombre de venta en el mercado comprar dolsa de kamagra medicina neurontin cap para que es su uso portal seguro para comprar kamagra viagra barata y certificada comprar viagra en corrientes vendo una pastilla viagra comocomprar viagra soft tabs \"remedios caseros para el mal aliento\" viagra donde ycomo comprar comprar zenegra Вїcomo se toma ? como comprar viagra en madrid cialis sin receta
8月 17th, 2010 at 6:06 AM
6 valium price or tramadol hydrochloride dosing or viagra birth control discrimination or on line cialis delivered to ireland or phentermine hcl 15 mg or i lost weight with phentermine or phentermine and nipple discharge or paracetamol tramadol or valium orange pill or new tramadol tramadol shipped cod or 4 mg xanax bars or buy valium from south america or tramadol and celebrex or does tramadol show up in drug tests or nyquil mixed with xanax deadly or tramadol m print on one side or viagra cialis levitra buy viagra or phentermine diet pills no rx or acai berry or adipex or cialis for paralysis patients or cheapest generic viagra and cialis pills or valium contraindication narrow angle glaucoma or ledalite soma or loss pills adipex or phentermine foreign pharmacy or viagra users discussion or how to order adipex online or adipex online overnight fed ex or cialis levitra viagra index or xanax erection or can adipex be taken with or tramadol dog arthritis or us pharmacies no prescription valium or what dose viagra do or reviews for xanax or cialis works fast or review viagra or buy cialis buy cialis online dreampharmaceuticals or levitra viagra price or buy soma in florida or chrysler cialis or xanax makes pupils small or adipex buy meridia or parkinsons and valium or viagra steroids gif or xanax for ulcer or what does tramadol hydrochloride do or soma meds or adipex ionamin meridia phentermine weightloss or free adipex without perscription or
8月 17th, 2010 at 6:17 AM
6 price search tramadol or hair loss with use of phentermine or sibutramine in adipex or
8月 17th, 2010 at 6:23 AM
2 citalopram and tramadol interaction or taking soma and flexeril or erectile dysfunction babies viagra or
8月 17th, 2010 at 6:39 AM
6 online pharmacy phentermine rx or phentramine vs phentermine or tramadol 120 tabs $75 free shipping or
8月 17th, 2010 at 6:41 AM
7 long term phentermine affects or enhancing the viagra experience or viagra safe or
8月 17th, 2010 at 7:02 AM
6 lethal mg of xanax or xanax with a money order or yellow xanax footballs or does xanax make you drowsy or sprzedam adipex meridia or pills care phentermine or what is the generic for adipex or how viagra works video or xanax toxic level or valium honduras or mixing viagra and vicodin or manufacture of adipex or expected weight loss with phentermine or maryland cialis tadalafil viagra or xanax dose size or phentermine without a prescription and or tramadol stomach cramps or tramadol stomach cramps or accepting c o d phentermine or side effects of tramadol 50mg or tramadol dosage calculations for dogs or thyroid phentermine or adipex sprzedawca or low cost prescription phentermine or but adipex without a prescription or can you take half a cialis or order xanax no rx mexico or viagra utah or buy cheap phentermine mg tabs or safe cialis dosage or peach colored xanax or soma myth or viagra is contraindications with what drug or generic cialis 20mg best buy mexico or adipex overnight shipping sale or valium polygraph or taking valium when pregnant or generic cialis mexican or adipex buy online phentermine or viagra premature ejeculation or valium dosage for cats or how long does valium work or soma environmental engineering or cialis cause of blood shot eyes or get adipex prescription or buy cialis by check or is phentermine available or does xanax cause heart failure or xanax treatment acute panic attacks or buying phentermine on line or
8月 27th, 2010 at 12:00 AM
7 phentermine in phoenix az or tramadol safety or no prescription saturday delivered tramadol or