Does the NSString returned from NSArray objectAtIndex as autorelease or retain - objective-c

I have a string returned back from an array, just wonder if I need to release it after using it.

Have a look at this blog post, which does a great job summarizing the rules for Objective C memory management: http://interfacelab.com/objective-c-memory-management-for-lazy-people/.
In particular, rule #1 applies here - you only need to release an object if you own it and you own it if you alloc, copy or new it (or if you explicitly retained it). You didn't do any of those things, so you don't need to release it.
Whether it's autoreleased or not depends on how the string was originally created but you don't need to worry about that since you are not responsible for releasing it.

The objects returned from -objectAtIndex: are technically both.
The code looks something like this:
-(id) objectAtIndex:(NSUInteger) index
{
return [[objects_[index] retain] autorelease];
}
So they don't belong to you, but if you remove it from the array, it won't be immediately deallocated.

autoreleased.
That is with (almost?) any object returned by a method, it would make memory management overly complicated if it wasn't. It is why we all love autorelease.

Related

How does retainCount work?

I have a problem with retainCount
NSLog(#"%i", [self.albumReceiver retainCount]);
self.albumReceiver = [[[FacebookAlbumsDelegateReceiver alloc] init: self] autorelease];
NSLog(#"%i", [self.albumReceiver retainCount]);
The retain count on the first line is 0 but when it gets to third line is 3.
The property on self.albumReceiver is retain property... But as far as i can see it should be 2 where other later retain count should went to 1 since it was autorelease later.
NSLog(#"%i", [self.albumReceiver retainCount]);
albumReceiver = [[[FacebookAlbumsDelegateReceiver alloc] init: self];
NSLog(#"%i", [self.albumReceiver retainCount]);
the retain count start with 0 and in this case the second retain count print 2....
Can somebody give some idea of how this retain and release work....
I thought without 'self' keyword, it will ignore the setter call is it? But if i put autorelease on the second example, i will have error.
Firstly, the retain count is an implementation detail that you should not be overly concerned with. You should really only care about ownership.
Having said that, the explanation for what you are seeingis as follows:
The retain count on the first line is 0
That's because self.albumReceiver is nil at that point. On real objects, you will never see a retain count of 0 (in the current implementation of Foundation).
when it gets to third line is 3
Normally you would expect the retain count to be 2, +1 for the alloc and +1 for assignment to a retain property. However, the init: method might cause some other object to retain it, so might the setter for the property. Another object observing the property might choose to retain the object too. In short, unless you know the exact implementation of all the methods involved and you know for sure nothing is using KVO on albumReceiver, all you can say about the retain count is that self has ownership of it (NB ownership is not exclusive, other things may also have ownership). This is why you shouldn't pay too much attention to retain counts.
Can somebody give some idea of how this retain and release work
Yes. You need to think in terms of ownership. Certain methods give you an object that you own. These are any method starting with alloc, any method starting with new, any method starting with copy or mutableCopy and -retain. If you receive an object in any other way, you do not own it. That includes receiving them as a return result of a method, ass parameters of a method or as by reference parameters of a method or as global or static variables.
If you own an object, you must relinquish ownership by either releasing or autoreleasing it, or it will leak. If you do not own an object, you must not release or autorelease it.
I find that it is best to think of "you" in the above as meaning "the scope in which the object reference was declared".
Anyway, I recommend you to read Apple's Memory Management Rules for the definitive explanation and not to trust answers here. If you look at the original edit for this answer, you'll see that I got the rules slightly wrong because they have been tightened up since I last read them.
Do not use retainCount. (For situations where it’s appropriate to use it, see this website.) Further reading: blog post by bbum, previous SO thread one, thread two. Also note that retainCount is deprecated in recent SDKs. It’s a good idea to pay attention to the deprecation warnings, and even better idea to turn all warnings into errors.
It is generally a bad idea to pay any attention to the retainCount of an object in Objective-C because it is usually impossible to know which secret parts of the frameworks feel a need to retain the object.
In the case you cite where you are adding the object to the autorelease pool, the autorelease pool will presumably be retaining the object until it comes time to flush the pool (during the runloop). This probably explains why the retain count is higher for the autoreleased object.
Note the use of the words "presumably" and "probably" in the above paragraph. I have no idea if this is actually what is happening inside the Cocoa/Cocoa Touch frameworks. This is the problem with using retainCount, you have no way of knowing what the retain count should be at any moment.
If you retain the object (or create it with a method name that contains alloc, copy, mutableCopy or new), you release it. The frameworks are free to also retain the object and they will release it when they are ready. When the retain count reaches zero it will be dealloced.
Update: Having looked at the GNUStep source code for NSObject and NSAutoreleasePool my possible explanation above probably isn't what is happening. However, I have no way to check for sure because I can't see Apple's implementation of these two objects. Even more reason not to trust retainCount or any inferences from it.
The only rule that really exists in environments with manual memory management is
If you use alloc, copy, mutableCopy, new
release it. Otherwise DON'T. retainCounts don't really work for debugging. See here

difference between – initWithRequest:delegate: and +connectionWithRequest:delegate

I want to know the difference between –initWithRequest:delegate: and +connectionWithRequest:delegate: of NSURLConnection?
Just the first one is no-aotorelease object and second is autorelease?
I want to know which one should I use in my ios code?
You've already pointed out the difference
For iOS codes, it's best to use use Alloc/init rather than convenience auto release functions because they stay around after you are done using them and there is no way for you to release them
Use autorelease when it's not possible to know when to call release (such as when you are returning a object that is not being retained elsewhere) The closest autorelease pool will free the memory the next time the pool is drained.
If you do use alloc/init, remember to call release, otherwise it will linger on in the memory
All methods in Objective-C that starts with init require to be called only after alloc method. Also init-method returns non-autoreleased object.
All methods that starts from name similar to class name, for example, [NSString string], [NSArray array] and others returns autoreleased objects and don't require precalled alloc method.
Returning to you question: you can use any of that approaches: alloc + initWithRequest:delegate: or connectionWithRequest:delegate: but be sure to release object in first case.
I think you pointed out the only difference.
I use the +connectionWithRequest:delegate: method
I think something internal is retaining the connection until it fails or finishes

Object release behavior in iPhone

If I release mainPath in following example the program gives an error (because I’m releasing an object with zero counter)
NSString *mainPath = [NSString stringWithFormat:#"%#/Documents/downloadFile.plist",NSHomeDirectory()];
NSLog(#"address is = %#",mainPath);
[mainPath release]; //Program failed here
But the following code works fine.
NSString *aa=#"hiiiii";
[aa release];
Can anyone explain this?
Actually I’m not clear about the pointer concept (give a suitable link to clear it)
Constant NSStrings are a special case. They are allocated statically at compile time and can't be deallocated. You can send release to a constant string as many times as you like, it'll never get deallocated. This is achieved in the current implementation by setting the retain count to INT_MAX which is treated as a special value meaning "don't decrement me on release".
You should read the Cocoa Memory Management Guide or at least the Objective-C Tutorial by Scott Stevenson. (Really. Do it, you’ll save a lot of time in the long run.) The difference is that the first string is autoreleased, you do not own it and should not release it. The second string is special, I think it’s not allocated on the heap at all and the release is essentially a no-op here.
String with format is a convenience method that autoreleases the string so in this case you are likely to be sending a release message to an already deallocated object.
In your second example, you are creating the string statically so retain counts don't apply.
You don't need to release your objects in either of those cases.
As a rule of thumb, if you didn't use init (or initWithFoo:) to create the object, and didn't deliberately use retain to retain the object (plus couple of other rarer cases), you don't need to use release.

Reference on when to release in Objective-C

I'm having a recurring problem in Objective-C. I'm either releasing things too many time, or not enough. or perhaps I'm not retaining them enough...
Can someone point me at a good reference that will give me a rule of thumb on when I need to retain and release?
For example:
I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?
if I alloc an object and only need it in that method, do I need to release it? retain it?
Obviously, if I retained something, I needtorelease it, but beyond that, I get a bit lost.
The rules are generally pretty simple. If you get an object in one of the following ways:
id obj = [[MyObject alloc] init];
id obj = [myObject retain];
id obj = [myObject copy];
id obj = [myObject mutableCopy];
then you need to release it at some point -- in the same method, or your dealloc method, generally. In other words, balance your calls to alloc, retain, copy, and mutableCopy with a matching release call.
I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?
This happens rarely. The documentation for the called method should specify that you are responsible for releasing the returned object; otherwise, you should assume you're receiving an autoreleased object.
if I alloc an object and only need it in that method, do I need to release it? retain it?
Yes, you need to release it (but you don't need to retain it). (You can also use one of the convenience methods that return an autoreleased object if you're only going to use it in that method.)
There is one and only one canonical reference: Apple's Memory Management Guide for Cocoa or iPhone.

Differences in return object pointer?

Can someone explain the difference between these two, the first one is taken from allowing xcode to automatically generate the declaration, the last one is taken from an example in "Cocoa Programming" by Aaron Hillegass.
- (NSString*)planetName {
return [[planetName retain] autorelease];
}
.
- (NSString*)planetName {
return planetName;
}
I am just curious whats going on, my understanding was that the method is returning a pointer to either nil or an existing string object. I don't understand the reason for retaining and then adding to the autorelease pool?
Consider:
NSString *planetName = [myPlanet planetName];
[myPlanet setPlanetName: #"Bob"];
[planetName length];
Without [[planetName retain] autorelease], the above will very likely crash.
retain/autorelease puts the object into the current thread's autorelease pool. That effectively guarantees that the object will remain valid until the pool is drained, which is typically after the current event -- user event, timer firing, etc... -- is done processing.
(1) Use #property and #synthesize. It generates correct getter/setters for you.
(2) Read the Cocoa Memory Management guide. It answers all of these questions quite well.
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
In both cases, yes, they are both returning a pointer to either nil or the string object.
The difference is that the first code block handles memory management, the second does not. The second code block is assuming you are managing planetName somewhere else in your class instance, whereas in the first code block Apple is being as conservative as possible in keeping that memory from leaking. By putting the memory in the current autorelease pool it will be destroyed with the pool.
My recommendation would be to stick with the latter case and to be a little wiser about managing your own object instances than what XCode is auto-generating for you.