Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

iphone - Autorelease for beginners

I found this very useful definition here:

When you autorelease, you're basically saying: "I don't need this any longer, but anyone else is free to pick it up (before the auto release pool is drained)". When you explicitly relase an object you're saying: "I don't need this any longer and unless anyone else has already said otherwise (acquired), it should be deallocated immediately."

Consequently, autorelease is not normally the wrong thing to. It is required when you want to pass objects back to the sender of a message without requiring the sender to take care of releasing the object.

However, I am still wondering what the second paragraph means. Autorelease is not normally the wrong thing to do... I thought it's really memory intensive, so it should naturally be the wrong thing to do. But as for the last sentence, I'm afraid I don't get it.

When do I really need to use autorelease and what would be a good example / rule of thumb that beginners can easily remember?

Thanks for any suggestions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Autorelease is not normally the wrong thing to do... I thought it's really memory intensive, so it should naturally be the wrong thing to do.

It's not "memory intensive" at all. If you allocate and autorelease a very large number of objects, such as in a loop, or a smaller number of large objects, you could run into problems. But autorelease just delays the release of objects that you're creating anyway, and which may or may not even be deallocated when the release does happen (the autoreleased objects may also be retained by other objects).

If you can release an object immediately, do that. If you need to autorelease, then do that and don't worry about the memory. If you're creating lots of objects in each iteration of a loop, you might want to consider either using your own autorelease pool or creating said objects with alloc/init so that you can release them immediately.

But as for the last sentence, I'm afraid I don't get it.

If a method had to release every object that it created before returning, there'd be no way to return an object without requiring the caller to release the returned object. Autorelease allows a method to create an object and release it, but to defer that release until the caller has had a chance to use and possibly retain the returned object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...