I’m Delphi programmer and very new to Cocoa.
at first I tried this :
-(void)awakeFromNib
{
int i;
NSString *mystr;
for (i=1;i<=24;i++)
{
[comboHour addItemWithObjectValue:i];
}
}
But it didn’t work. Then I tried to search on Google but no luck.
After experimenting about 30 min, I come with this:
-(void)awakeFromNib
{
int i;
NSString *mystr;
for (i=1;i<=24;i++)
{
mystr = [[NSString alloc]initWithFormat:@"%d",i];
[comboHour addItemWithObjectValue:mystr];
//[mystr dealloc];
}
}
My questions are:
- Is this the right way to do that ?
- Do I always need to alloc new
NSString to change its value from
integer ? - When I uncomment [mystr dealloc],
why it won’t run ? - Does it cause memory leak to alloc
without dealloc ? - Where can I find basic tutorial like
this on internet ?
Thanks in advance
Generally yes; however, there are more convenient ways to create strings (and many other types of objects) than using
allocandinit(see autorelease pools below)You can pass any Objective-C object type to
addItemWithObjectValue:, includingNSStringandNSNumberobjects. Both classes have a number of convenient class methods you can use to create new instances, for example:Never call
dealloc. Usereleaseinstead.Cocoa objects are reference counted, like COM objects in Delphi. Like COM, you call
releasewhen you’re finished with an object. When an object has no more references it is automatically deallocated.Unlike COM, Cocoa has “autorelease pools”, which allows you to, for example, create a new NSString instance without having to worry about calling
releaseon it.For example:
[NSString stringWithFormat:@"%d", 123]creates an “autoreleased” string instance. You don’t have toreleaseit when you’re done. This is true of all methods that return an object, exceptnewandinitmethods.Yes, unless you’re using garbage collection.
See Practical Memory Management