Noitidart
Noitidart

Reputation: 37238

Reuse Allocated Class - Any Need to Release It?

I'm pretty new to objective-c, I had a question. Is it ok to reuse the NSString_class that we allocated?

NSString_class = [NSString alloc]

Reuse like this:

str1 = [NSString_class initWithUTF8String: @"blah"]
str2 = [NSString_class initWithUTF8String: @"blah"]

and to release I dont have to release NSString_class right? Just the str1 and str2?

[str1 release]
[str2 release]

Upvotes: 0

Views: 45

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

A couple of things....

It would be very unusual to split alloc and init into two different steps.

Your variable naming is also misleading. The thing you get back from allocating an instance is an object that you assign to a pointer; it's not a "..._class".

That being said, you've called alloc once, which means you only have one object. If you change its properties in order for str2 to point to the string you want, you've changed it for str1 as well.

Also, one alloc means +1 for the retain count, making two releases incorrect.

Upvotes: 2

Related Questions