Aldee
Aldee

Reputation: 4528

Objective C: Allocating Memory

I am new to Objective C and here is my confusion:

When is it applicable to allocate memory for an instance?. Like this:

When is it applicable to use this...

NSString *str = [[NSString alloc]init];

and to use this...

- (NSString *) formatStr:(NSString *) str{
   NSString *str = (NSString *) str;
...
.....
.......
}

and even creating UIActionSheet, it uses alloc but in other UI elements, it does not..

What exactly the reason and when shall it be done?

Thanks fellas.. :D

Upvotes: 0

Views: 942

Answers (3)

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

when you create an instance using alloc+init OR you get an instance through a method that has init in the name (a convention, e.g. initWithString) you are said to own the object, this is, you must not retain it (its ref counter is already set to 1) and need to eventually release it when you are done with it. When you receive an instance by calling a method which hasn't get init in the name (rule on thumb but you should always check documentation) this means that you are not the owner of the object, i.e. the object might be released at any time, even while you are using it. Usually methods such as stringWithFormat will return autoreleased objects which will be around until the end of the event cycle (unless you claim ownership by calling retain on the string). I strongly recommend reading the cocoa memory management guide.

NSString *str = [[NSString alloc]init]; //you own the object pointed to by str. Its retain count is 1. If you don't call release this will be a memory leak.


- (NSString *) formatStr:(NSString *) str{
   NSString *str = (NSString *) str; //you don't own str. btw, you don't need casting here
//using str here might throw exception if its owner has released it 
  [str retain]; //you own str now. you can do whatever you want with it. It's yours
.......
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

In addition to the "normal" allocation route (i.e. through [[MyClass alloc] init]) some classes provide so called "factory methods". These are class methods that allocate objects internally. The advantage of using factory methods is that they can create a suitable subclass to return to the caller. In both cases, though, the allocation is ultimately done by alloc/init.

Upvotes: 2

Jessedc
Jessedc

Reputation: 12460

Objective C's alloc method handles allocating memory, you don't have to worry about allocating, just managing the retain and release cycles.

checkout this About Memory Management article from Apple

Upvotes: 0

Related Questions