开发者

Releasing Objects When Do and When dont I have too

Here is some code I have in my app that I DIDNT release. When I try to release I get a Program received signal: “EXC_BAD_ACCESS”. exception and the app crashes. If I dont try to release 开发者_StackOverflowit the app runs fine. Do I need to call a release message on these objects? Any idea what could be going on here?

        NSString *sA = legA.text;
        NSArray *firstLeg = [sA componentsSeparatedByString:@","]; 


[sA release]; //works ok
[firstLeg release]; //sends the bad access exception and crashes the app


Both of them don't need to be -released.

I suggest you read the Memory Management Rules. You need to -release an object if and only if the current scope is an owner of that object. You become an owner only when the object is received as

  • [[Foo alloc...] init...]
  • [foo new...]
  • [foo copy...] or [foo mutableCopy...]
  • [foo retain]

in all other cases, you should never -release it. As .text and -componentsSeparatedByString: are not one of these methods, there's no need to -release sA and firstLeg.


I'm not great at objective c, but shouldn't there be a [[NSArray alloc] init] thing somewhere? Or does the componentsSeperatedBySTring replace it?


No, you may only send release to objects you have ownership off: those you get from alloc/init, retain or copy.


Run, don't walk, to the "Object Ownership" section of the Memory Management Programming Guide for Cocoa and read up on the rules for when you "own" an object. You only release objects you own, so in this case you don't want to release them.


Several correct answers so far, but nobody has yet posted the Cocoa Memory Management Rules which should be compulsory when answering a "do I own this" question..

Edit: must type faster...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜